summaryrefslogtreecommitdiffstats
path: root/txr.1
blob: 5781418cae792f0482d57c8f474713bd2616d31d (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
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
.\"Copyright (C) 2011, Kaz Kylheku <kaz@kylheku.com>.
.\"All rights reserved.
.\"
.\"BSD License:
.\"
.\"Redistribution and use in source and binary forms, with or without
.\"modification, are permitted provided that the following conditions
.\"are met:
.\"
.\"  1. Redistributions of source code must retain the above copyright
.\"     notice, this list of conditions and the following disclaimer.
.\"  2. Redistributions in binary form must reproduce the above copyright
.\"     notice, this list of conditions and the following disclaimer in
.\"     the documentation and/or other materials provided with the
.\"     distribution.
.\"  3. The name of the author may not be used to endorse or promote
.\"     products derived from this software without specific prior
.\"     written permission.
.\"
.\"THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
.\"IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
.\"WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

.TH "TXR" 1 2012-04-20 "Utility Commands" "Txr Text Processing Language" "Kaz Kylheku"
.SH NAME
txr \- text processing language (version 65)
.SH SYNOPSIS
.B txr [ options ] query-file { data-file }*
.sp
.SH DESCRIPTION
.B TXR
is a language oriented toward processing text from files or streams, using
multiple programming paradigms.

A
.B TXR
script is called a query, and it specifies a pattern which matches (a prefix
of) an entire file, or multiple files.  Patterns can consists of large
chunks of multi-line freeform text, which is matched literally
against material in the input sources. Free variables occurring in the pattern
(denoted by the @ symbol) are bound to the pieces of text occurring in the
corresponding positions. If the overall match is successful, then
.B TXR
can do one of two things: it can report the list of variables which were bound,
in the form of a set of variable assignments which can be evaluated by the
.B eval
command of the POSIX shell language, or generate a custom report according
to special directives in the query. Patterns can be arbitrarily complex,
and can be broken down into named pattern functions, which may be mutually
recursive. TXR patterns can work horizontally (characters within a line)
or vertically (spanning multiple lines). Multiple lines can be treated
as a single line.


In addition to embedded variables which implicitly match text, the
.B TXR
query language supports a number of directives, for matching text using regular
expressions, for continuing a match in another file, for searching through a
file for the place where an entire sub-query matches, for collecting lists, and
for combining sub-queries using logical conjunction, disjunction and negation,
and numerous others.  

Furthermore, embedded within TXR is a powerful Lisp dialect.  TXR Lisp supports
functional and imperative programming, and provides data types such as symbols,
strings, vectors, hash tables with weak reference support, lazy lists, and
arbitrary-precision (bignum integers).

.SH ARGUMENTS AND OPTIONS

Options which don't take an argument may be combined together.
The -v and -q options are mutually exclusive. Of these two, the one which
occurs in the rightmost position in the argument list dominates.
The -c and -f options are also mutually exclusive; if both are specified,
it is a fatal error.

.IP -Dvar=value
Bind the variable
.IR var
to the value
.IR value
prior to processing the query. The name is in scope over the entire
query, so that all occurrence of the variable are substituted and
match the equivalent text.  If the value contains commas, these
are interpreted as separators, which give rise to a list value.
For instance -Da,b,c creates a list of the strings "a", "b" and "c".
(See Collect Directive bellow). List variables provide a multiple
match. That is to say, if a list variable occurs in a query, a successful
match occurs if any of its values matches the text. If more than one
value matches the text, the first one is taken.

.IP -Dvar
Binds the variable
.IR var
to an empty string value prior to processing the query.

.IP -q
Quiet operation during matching. Certain error messages are not reported on the
standard error device (but the if the situations occur, they still fail the
query). This option does not suppress error generation during the parsing
of the query, only during its execution.

.IP -d
Invoke the interactive txr debugger. See the DEBUGGER section.

.IP -v
Verbose operation. Detailed logging is enabled.

.IP -b
Suppresses the printing of variable bindings for a successful query, and the
word .
IR false
for a failed query. The program still sets an appropriate
termination status.  Bindings are implicitly suppressed if the TXR query
performs an output operation on any file stream other than *stddebug*.
(Internal streams like string streams do not count as output.)

.IP -B
Force the printing of variable bindings for a successful query, and the
word .
IR false
for a failed query, even if the program produced output.

.IP "-l or --lisp-bindings"
Print the variable bindings in Lisp syntax instead of shell syntax.

.IP "-a num"
The decimal integer argument specifies the maximum number of array dimensions
to use for variables arising out of collect. The default is 1. Additional
dimensions are expressed using numeric suffixes in the generated variable
names.
For instance, consider the three-dimensional list arising out of a triply
nested collect: ((("a" "b") ("c" "d")) (("e" "f") ("g" "h"))).
Suppose this is bound to a variable V.  With -a 1, this will be
reported as:

  V_0_0[0]="a"
  V_0_1[0]="b"
  V_1_0[0]="c"
  V_1_1[0]="d"
  V_0_0[1]="e"
  V_0_1[1]="f"
  V_1_0[1]="g"
  V_1_1[1]="h"

The leftmost bracketed index is the most major index. That is to say,
the dimension order is: NAME_m_m+1_..._n[1][2]...[m-1].

.IP "-c query"
Specifies the query in the form of a command line argument. If this option is
used, the query-file argument is omitted. The first non-option argument,
if there is one, now specifies the first input source rather than a query.
Unlike queries read from a file, (non-empty) queries specified as arguments
using -c do not have to properly end in a newline. Internally, TXR
adds the missing newline before parsing the query. Thus -c "@a"
is a valid query which matches a line.

Example:

  # read two lines "1" and "2" from standard input,
  # binding them to variables a and b. Standard
  # input is specified as - and the data
  # comes from shell "here document" redirection.

  txr -c "@a
  @b" - <<!
  1
  2
  !

  Output:
  a=1
  b=2

The @; comment syntax can be used for better formatting:

  txr -c "@;
  @a
  @b"

.IP "-f query-file"
Specifies the file from which the query is to be read, instead of the
query-file argument. This is useful in #! scripts. (See Hash Bang Support
below).

.IP --help
Prints usage summary on standard output, and terminates successfully.

.IP --version
Prints program version standard output, and terminates successfully.

.IP --
Signifies the end of the option list. This option does not combine with others, so for instance -b- does not mean -b --, but is an error.

.IP -
This argument is not interpreted as an option, but treated as a filename
argument. After the first such argument, no more options are recognized. Even
if another argument looks like an option, it is treated as a name.
This special argument - means "read from standard input" instead of a file.
The query file, or any of the data files, may be specified using this option.
If two or more files are specified as -, the behavior is system-dependent.
It may be possible to indicate EOF from the interactive terminal, and
then specify more input which is interpreted as the second file, and so forth.

.PP
After the options, the remaining arguments are files. The first file argument
specifies the query, and is mandatory.  A file argument consisting of a single
- means to read the standard input instead of opening a file. A file argument
which begins with an exclamation symbol means that the rest of the argument is
a shell command which is to be run as a coprocess, and its output read like a
file.

.PP
.B TXR
begins by reading the query. The entire query is scanned, internalized
and then begins executing, if it is free of syntax errors.  The reading of
data, on the other hand, is lazy.  A file isn't opened until the query demands
material from that file, and then the contents are read on demand, not all at
once.

If no files arguments are specified on the command line, it is up to the
query to open a file, pipe or standard input via the @(next) directive
prior to attempting to make a match. If a query attempts to match text,
but has run out of files to process, the match fails.

.SH STATUS AND ERROR REPORTING
.B TXR
sends errors and verbose logs to the standard error device.  The following paragraphs apply when
.B TXR
is run without enabling verbose mode. If verbose mode is enabled, then
.B TXR
issues diagnostics on the standard error device even in situations which are
not erroneous.

If the command line arguments are incorrect, or the query has a malformed
syntax, or fails to match,
.B TXR
issues an error diagnostic and terminates with a failed status.

If the query is accepted, but fails to execute, either due to a
semantic error or due to a mismatch against the data,
.B TXR
terminates with a failed status, it also prints the word
.IR false
on standard output. (See NOTES ON FALSE below).  Printing of false
is suppressed if the query executed one or more @(output) directive
directed to standard output.

If the query is well-formed, and matches, then
.B TXR
issues no diagnostics on standard error (except in the case of verbose
reporting enabled by -v).  If no variables were bound in the query, then
nothing is printed on standard output.  If the query has matched one or more
variables, then these variables are printed on standard output, in the form of
a shell script which, when evaluated, will cause shell variables to be
assigned.  Printing of these variables is suppressed if the query executed one
or more @(output) directive directed to standard output.

.SH BASIC QUERY SYNTAX AND SEMANTICS

.SS Comments

A query may contain comments which are delimited by the sequence @; and
extend to the end of the line. No whitespace can occur between the @ and ;.
A comment which begins on a line swallows that entire line, as well as the
newline which terminates it. In essence, the entire comment disappears.
If the comment follows some material in a line, then it does not consume
the newline. Thus, the following two queries are equivalent:

 1.  @a@; comment: match whole line against variable @a
     @; this comment disappears entirely
     @b

 2.  @a
     @b

The comment after the @a does not consume the newline, but the
comment which follows does. Without this intuitive behavior,
line comment would give rise to empty lines that must match empty
lines in the data, leading to spurious mismatches.

Instead of the ; character, the # character can be used. This is
an obsolescent feature.


.SS Hash Bang Support

If the first line of a query begins with the characters #!,
that entire line is deleted from the query. This allows
for TXR queries to be turned into standalone executable programs in the POSIX
environment.

Shell example: create a simple executable program called "twoline.txr" and
run it. This assumes txr is installed in /usr/bin.

  $ cat > twoline.txr
  #!/usr/bin/txr
  @a
  @b
  [Ctrl-D]
  $ chmod a+x twoline.txr
  $ ./twoline.txr -
  1
  2
  [Ctrl-D]
  a=1
  b=2

A script written in this manner will not pass options to txr.  For
instance, if the above script is invoked like this

  ./twoline.txr -Da=42

the -D option isn't passed down to txr; -Da=42 is an ordinary
argument (which the script will try to open as an input file).
This behavior is useful if the script author wants not to
expose the txr options to the user of the script.

However, if the hash bang line can use the -f option:

  #!/usr/bin/txr -f

Now, the name of the script is passed as an argument to the -f option,
and TXR will look for more options after that.

.SS Whitespace

Outside of directives, whitespace is significant in TXR queries, and represents
a pattern match for whitespace in the input.  An extent of text consisting of
an undivided mixture of tabs and spaces is a whitespace token.  

Whitespace tokens match a precisely identical piece of whitespace in the input,
with one exception: a whitespace token consisting of precisely one space has a
special meaning. It is equivalent to the regular expression @/[ ]+/: match
an extent of one or more spaces (but not tabs!)

Thus, the query line "a b" (one space) matches texts like "a b", "a   b", et
cetera (arbitrary number of tabs and spaces between a and b).  However "a  b"
(two spaces) matches only "a  b" (two spaces).

For matching a single space, the syntax @\ can be used (backslash-escaped
space).

It is more often necessary to match multiple spaces, than to exactly
match one space, so this rule simplifies many queries and adds inconvenience
to only few.

In output clauses, string and character literals and quasiliterals, a space
token denotes a space.

.SS Text

Query material which is not escaped by the special character @ is
literal text, which matches input character for character. Text which occurs at
the beginning of a line matches the beginning of a line.  Text which starts in
the middle of a line, other than following a variable, must match exactly at
the current position, where the previous match left off. Moreover, if the text
is the last element in the line, its match is anchored to the end of the line.

An empty query line matches an empty line in the input. Note that an
empty input stream does not contain any lines, and therefore is not matched
by an empty line. An empty line in the input is represented by a newline
character which is either the first character of the file, or follows
a previous newline-terminated line.  

Input streams which end without terminating their last line with a newline are
tolerated, and are treated as if they had the terminator.

Text which follows a variable has special semantics, discussed in the
section Variables below.

A query may not leave unmatched material in a line which is covered by the
query.  However, a query may leave unmatched lines.

In the following example, the query matches the text, even though
the text has an extra line.

 Query:         Four score and seven
                years ago our

 Text:          Four score and seven
                years ago our
                forefathers

In the following example, the query
.B fails
to match the text, because the text has extra material on one
line.

 Query:         I can carry nearly eighty gigs
                in my head

 Text:          I can carry nearly eighty gigs of data
                in my head

Needless to say, if the text has insufficient material relative
to the query, that is a failure also.

To match arbitrary material from the current position to the end
of a line, the "match any sequence of characters, including empty"
regular expression @/.*/ can be used. Example:

 Query:         I can carry nearly eighty gigs@/.*/

 Text:          I can carry nearly eighty gigs of data

In this example, the query matches, since the regular expression
matches the string "of data". (See Regular Expressions section below).

Another way to do this is:

 Query:         I can carry nearly eighty gigs@(skip)


.SS Special Characters in Text

Control characters may be embedded directly in a query (with the exception of
newline characters). An alternative to embedding is to use escape syntax.
The following escapes are supported:

.IP @\e<newline>
A backslash immediately followed by a newline introduces a physical line
break without breaking up the logical line. Material following this sequence
continues to be interpreted as a continuation of the previous line, so
that indentation can be introduced to show the continuation without appearing
in the data.
.IP @\e<space>
A backslash followed by a space encodes a space. This is useful in line
continuations when it is necessary for leading spaces to be preserved.
For instance the two line sequence

   abcd@\
     @\  efg

is equivalent to the line

  abcd  efg

The two spaces before the @\ in the second line are consumed. The
spaces after are preserved.

.IP @\ea
Alert character (ASCII 7, BEL).
.IP @\eb
Backspace (ASCII 8, BS).
.IP @\et
Horizontal tab (ASCII 9, HT).
.IP @\en
Line feed (ASCII 10, LF). Serves as abstract newline on POSIX systems.
.IP @\ev
Vertical tab (ASCII 11, VT).
.IP @\ef
Form feed (ASCII 12, FF). This character clears the screen on many
kinds of terminals, or ejects a page of text from a line printer.
.IP @\er
Carriage return (ASCII 13, CR).
.IP @\ee
Escape (ASCII 27, ESC)
.IP @\exHEX
A @\ex followed by a sequence of hex digits is interpreted as a hexadecimal
numeric character code. For instance @\ex41 is the ASCII character A.
.IP @\eOCTAL
A @\e followed by a sequence of octal digits (0 through 7) is interpreted
as an octal character code. For instance @\e010 is character 8, same as @\eb.
.PP

Note that if a newline is embedded into a query line with @\en, this
does not split the line into two; it's embedded into the line and
thus cannot match anything. However, @\en may be useful in the @(cat)
directive and in @(output).

.SS International Characters

.B TXR
represents text internally using wide characters, which are used to represent
Unicode code points. The query language, as well as all data sources, are
assumed to be in the UTF-8 encoding.  In the query language, extended
characters can be used directly in comments, literal text, string literals,
quasiliterals and regular expressions.  Extended characters can also be
expressed indirectly using hexadecimal or octal escapes.
On some platforms, wide characters may be restricted to 16 bits, so that
.B TXR
can only work with characters in the BMP (Basic Multilingual Plane)
subset of Unicode.

.B TXR
does not use the localization features of the system library;
its handling of extended characters is not affected by environment variables
like LANG and L_CTYPE. The program reads and writes only the UTF-8 encoding.

If
.B TXR
encounters an invalid bytes in the UTF-8 input, what happens depends on the
context in which this occurs. In a query, comments are read without regard
for encoding, so invalid encoding bytes in comments are not detected. A comment
is simply a sequence of bytes terminated by a newline.  In lexical elements
which represent text, such as string literals, invalid or unexpected encoding
bytes are treated as syntax errors. The scanner issues an error message,
then discards a byte and resumes scanning.  Certain sequences pass through the
scanner without triggering an error, namely some UTF-8 overlong sequences.
These are caught when when the lexeme is subject to UTF-8 decoding, and treated
in the same manner as other UTF-8 data, described in the following paragraph.

Invalid bytes in data are treated as follows. When an invalid byte is
encountered in the middle of a multibyte character, or if the input
ends in the middle of a multibyte character, or if a character is extracted
which is encoded as an overlong form, the UTF-8 decoder returns to the starting
byte of the ill-formed multibyte character, and extracts just that byte,
mapping it to the Unicode character range U+DC00 through U+DCFF.  The decoding
resumes afresh at the following byte, expecting that byte to be the start
of a UTF-8 code.

.SS Regular Expression Directives

In place of a piece of text (see section Text above), a regular expression
directive may be used, which has the following syntax:

  @/RE/

where the RE part enclosed in slashes represents regular expression
syntax (described in the section Regular Expressions below).

Long regular expressions can be broken into multiple lines using a
backslash-newline sequence.  Whitespace before the sequence or after the
sequence is not significant, so the following two are equivalent:

  @/reg \e
    ular/

  @/regular/

There may not be whitespace between the backslash and newline.

Whereas literal text simply represents itself, regular expression denotes a
(potentially infinite) set of texts.  The regular expression directive
matches the longest piece of text (possibly empty) which belongs to the set
denoted by the regular expression. The match is anchored to the current
position; thus if the directive is the first element of a line, the match is
anchored to the start of a line. If the regular expression directive is the
last element of a line, it is anchored to the end of the line also: the regular
expression must match the text from the current position to the end of the
line.

Even if the regular expression matches the empty string, the match will fail if
the input is empty, or has run out of data. For instance suppose the third line
of the query is the regular expression @/.*/, but the input is a file which has
only two lines. This will fail: the data has line for the regular expression to
match. A line containing no characters is not the same thing as the absence of
a line, even though both abstractions imply an absence of characters.

Like text which follows a variable, a regular expression directive which
follows a variable has special semantics, discussed in the section Variables
below.

.SS Variables

Much of the query syntax consists of arbitrary text, which matches file data
character for character. Embedded within the query may be variables and
directives which are introduced by a @ character.  Two consecutive @@
characters encode a literal @.

A variable matching or substitution directive is written in one of several
ways:

  @NAME
  @{NAME}
  @*NAME
  @*{NAME}
  @{NAME /RE/}
  @{NAME (FUN [ ARGS ... ])}
  @{NAME NUMBER}

The forms with an * indicate a long match, see Longest Match below.
The last two forms with the embedded regexp /RE/ or number have special
semantics, see Positive Match below.

The identifier t cannot be used as a name; it is a reserved symbol which
denotes the value true. An attempt to use the variable @t will result
in an exception.  The symbol nil can be used as a variable name,
but it has special semantics, described in a section below.

When the @NAME form is used, the name itself may consist of any combination of
one or more letters, numbers, and underscores. It may not look like a number,
so that for instance 123 is not a valid name, but 12A is valid.  Case is
sensitive, so that @FOO is different from @foo, which is different from @Foo.

The braces around a name can be used when material which follows would
otherwise be interpreted as being part of the name. When a name is enclosed in braces, the following additional characters may be used as part of the name:

 ! $ % & * + - < = > ? \e ^ _ ~

The rule holds that a name cannot look like a number so +123 is not a name,
but these are valid names: a->b, *xyz*, foo-bar.

The syntax @FOO_bar introduces the name "FOO_bar", whereas @{FOO}_bar means the
variable named "FOO" followed by the text "_bar".   There may be whitespace
between the @ and the name, or opening brace. Whitespace is also allowed in the
interior of the braces. It is not significant.

If a variable has no prior binding, then it specifies a match. The
match is determined from some current position in the data: the
character which immediately follows all that has been matched previously.
If a variable occurs at the start of a line, it matches some text
at the start of the line. If it occurs at the end of a line, it matches
everything from the current position to the end of the line.

.SS Negative Match

If a variable is one of the plain forms @NAME, @{NAME},  @*NAME or @*{NAME},
then this is a "negative match".  The extent of the matched text (the text
bound to the variable) is determined by looking at what follows the variable,
and ranges from the current position to some position where the following
material finds a match. This is why this is called a "negative match": the
spanned text which ends up bound to the variable is that in which the match for
the trailing material did not occur.

A variable may be followed by a piece of text, a regular expression directive,
a function call, a directive, another variable, or nothing (i.e.  occurs at the
end of a line). These cases are discussed in detail below.

.SS Variable Followed by Nothing

If the variable is followed by nothing, the negative match extends from the
current position in the data, to the end of the line.  Example:

  pattern:      "a b c @FOO"
  data:         "a b c defghijk"
  result:       FOO="defghijk"

.SS Variable Followed by Text

For the purposes of determining the negative match, text is defined as a
sequence of literal text and regular expressions, not divided by a directive.
So for instance in this example:

  @a:@/foo/bcd e@(maybe)f@(end)

the variable @a is considered to be followed by ":@/foo/bcd e".

If a variable is followed by text, then the extent of the negative match is
determined by searching for the first occurrence of that text within the line,
starting at the current position. 

The variable matches everything between the current position and the matching
position (not including the matching position). Any whitespace which follows
the variable (and is not enclosed inside braces that surround the variable
name) is part of the text. For example:

  pattern:      "a b @FOO e f"
  data:         "a b c d e f"
  result:       FOO="c d"

In the above example, the pattern text "a b " matches the
data "a b ". So when the @FOO variable is processed, the data being
matched is the remaining "c d e f". The text which follows @FOO
is " e f". This is found within the data "c d e f" at position 3
(counting from 0).  So positions 0-2 ("c d") constitute the matching
text which is bound to FOO.

.SS Variable Followed by a Function Call or Directive

If the variable is followed by a function call, or a directive, the extent is
determined by scanning the text for the first position where a match occurs for
the regular expression, call or directive. (For a description of functions,
see FUNCTIONS.)

Note that the given variable and the function or directive are considered
in isolation. This means, for instance, that @var@(skip)text is a degenerate
form. The @(skip) will be processed alone, without regard for the trailing
text and so consume the input to the end of the line. The right way to
express the most probable intent of this is @{var}text.

Another degenerate case is @var@(bind ...), or in general, a variable
followed by some directive not used for matching text. Watch out for
the following pitfall:

 @a @b@(bind have_ab "y")

The intent here is that the variable b captures everything after the space to
the end of the line, and then the variable have_ab is set to "y". But since
@(bind) always succeeds, b captures an empty string, and then the whole line
fails if there is any material after the space. The right way to do this is:

 @a @b@(eol)@(bind have_ab "y")

That is to say, match an explicit @(eol) after the variable. This will
search for the end of the lne and capture the spanning text into b, as
intended.  The bind then happens afterward.

.SS Consecutive Variables

If an unbound variable specified a fixed-width match or a regular expression,
then the issue of consecutive variables does not arise. Such a variable
consumes text regardless of any context which follows it.

However, what if an unbound variable with no modifier is followed by another
variable? The behavior depends on the nature of the other variable.

If the other variable also has no modifier, this is a semantic error which
will cause the query to fail.  A diagnostic message will be issued, unless
operating in quiet mode via -q.  The reason is that there is no way to bind two
consecutive variables to an extent of text; this is an ambiguous situation,
since there is no matching criterion for dividing the text between two
variables.  (In theory, a repetition of the same variable, like @FOO@FOO, could
find a solution by dividing the match extent in half, which would work only in
the case when it contains an even number of characters.  This behavior seems to
have dubious value).

An unbound variable may be followed by one which is bound. The bound
variable is replaced by the text which it denotes, and the logic proceeds
accordingly.  Variables are never bound to regular expressions, so
the regular expression match does not arise in this case.
The @* syntax for longest match is available. Example:

  pattern:      "@FOO:@BAR@FOO"
  data:         "xyz:defxyz"
  result:       FOO=xyz, BAR=def

Here, FOO is matched with "xyz", based on the delimiting around the
colon. The colon in the pattern then matches the colon in the data,
so that BAR is considered for matching against "defxyz".
BAR is followed by FOO, which is already bound to "xyz".
Thus "xyz" is located in the "defxyz" data following "def",
and so BAR is bound to "def".

If an unbound variable is followed by a variable which is bound to a list, or
nested list, then each character string in the list is tried in turn to produce
a match. The first match is taken.

An unbound variable may be followed by another unbound variable which specifies
a regular expression or function call match. This is a special case called a
"double variable match".  What happens is that the text is searched using the
regular expression or function.  If the search fails, than neither variable is
bound: it is a matching failure.  If the search succeeds, than the first
variable is bound to the text which is skipped by the search.  The second
variable is bound to the text matched by the regular expression or function.
Examples:

  pattern:      "@foo@{bar /abc/}"
  data:         "xyz@#abc"
  result:       foo="xyz@#", BAR="abc"


.SS Consecutive Variables Via Directive

Two variables can be de-facto consecutive in a manner shown in the
following example:

  @var1@(all)@var2@(end)

The @(all) directive does nothing other than assert that all clauses must
match. It has only one clause, @var2. So this is equivalent to just @var1@var2,
except that if both variables are unbound, no semantic error is identified in
this situation. The situation is handled as a variable followed by a directive.
Of course @var2 matches any position current position, and so @var1 ends up
with nothing.

Example 1: b matches at position 0 and a gets nothing:

  pattern:      "@a@(all)@b@(end)"
  data:         "abc"
  result:       a=""
                b="abc"

Example 2: *a specifies longest match (see Longest Match below), and so a gets
everything:

  pattern:      "@*a@(all)@b@(end)"
  data:         "abc"
  result:       a="abc"
                b=""



.SS Longest Match

The closest-match behavior for the negative match can be overridden to longest
match behavior. A special syntax is provided for this: an asterisk between the
@ and the variable, e.g:

  pattern:      "a @*{FOO}cd"
  data:         "a b cdcdcdcd"
  result:       FOO="b cdcdcd"

  pattern:      "a @{FOO}cd"
  data:         "a b cdcdcd"
  result:       FOO="b "

In the former example, the match extends to the rightmost occurrence of "cd",
and so FOO receives "b cdcdcd".  In the latter example, the *
syntax isn't used, and so a leftmost match takes place. The extent
covers only the "b ", stopping at the first "cd" occurrence.

.SS Positive Match

There are syntax variants of variable syntax which have an embedded expression
enclosed with the variable in braces:

 @{NAME /RE/}
 @{NAME (FUN [ARGS ...])}
 @{NAME NUMBER}

These specify a variable binding that is driven by a positive match derived
from a regular expression, function or character count, rather than from
trailing material (which is regarded as a "negative" match, since the
variable is bound to material which is
.B skipped
in order to match the trailing material). In the /RE/ form, the match
extends over all characters from the current position which match
the regular expression RE. (see Regular Expressions section below).
In the (FUN [ARGS ...]) form, the match extends over characters which
are matched by the call to the function, if the call
succeeds. Thus @{x (y z w)} is just like @(y z w), except that the region of
text skipped over by @(y z w) is also bound to the variable x.
See FUNCTIONS below.

In the NUMBER form, the match processes a field of text which
consists of the specified number of characters, which must be nonnegative
number.  If the data line doesn't have that many characters starting at the
current position, the match fails. A match for zero characters produces an
empty string.  The text which is actually matched by this construct
is all text within the specified field, but excluding leading and
trailing whitespace. If the field contains only spaces, then an empty
string is extracted.

This syntax is processed without consideration of what other
syntax follows.  A positive match may be directly followed by an unbound
variable.

.SS Symbol nil as a Variable

If the symbol nil is used as a variable, it behaves like a variable which
has no binding. Furthermore, no binding is created. @nil allows the
variable matching syntax to be used to skip material, in ways different
from and complementary to @(skip).

.SS Regular Expressions

Regular expressions are a language for specifying sets of character strings.
Through the use of pattern matching elements, regular expression is
able to denote an infinite set of texts.
.B TXR
contains an original implementation of regular expressions, which
supports the following syntax:
.IP .
(period) is a "wildcard" that matches any character.
.IP []
Character class: matches a single character, from the set specified by
special syntax written between the square brackets.
Supports basic regexp character class syntax; no POSIX
notation like [:digit:]. The regex tokens \es, \ed and \ew are
permitted in character classes, but not their complementing counterparts.
These tokens simply contribute their characters to the class.
The class [a-zA-Z] means match an uppercase
or lowercase letter; the class [0-9a-f] means match a digit or
a lowercase letter; the class [^0-9] means match a non-digit, et cetera.
The class [\ed.] means match a digit or the period character.
A ] or - can be used within a character class, but must be escaped
with a backslash. A ^ in the first position denotes a complemented
class, unless it is escaped by backslash. In any other position, it denotes
itself.  Two backslashes code for one backslash. So for instance
[\e[\e-] means match a [ or - character, [^^] means match any character other
than ^, and [\e^\e\e] means match either a ^ or a backslash. Regex operators
such as *, + and & appearing in a character class represent ordinary
characters. The characters -, ] and ^ occurring outside of a character class
are ordinary. Unescaped / characters can appear within a character class. The
empty character class [] matches no character at all, and its complement [^]
matches any character, and is treated as a synonym for the . (period) wildcard
operator.
.IP "\es, \ew and \ed"
These regex tokens each match a single character. 
The \es regex token matches a wide variety of ASCII whitespace characters
and Unicode spaces. The \ew token matches alphabetic word characters; it
is equivalent to the character class [A-Za-z_]. The \ed token matches
a digit, and is equivalent to [0-9].
.IP "\eS, \eW and \eD"
These regex tokens are the complemented counterparts of \es, \ew and \ed.
The \eS token matches all those characters which \es does not match,
\eW matches all characters that \ew does not match and \eD matches nondigits.
.IP empty
An empty expression is a regular expression. It represents the set of strings
consisting of the empty string; i.e. it matches just the empty string. The
empty regex can appear alone as a full regular expression (for instance the
.B TXR
syntax @// with nothing between the slashes)
and can also be passed as a subexpression to operators, though this
may require the use of parentheses to make the empty regex explicit.  For
example, the expression a| means: match either a, or nothing.  The forms
* and (*)  are syntax errors; though not useful, the correct way to match the
empty expression zero or more times is the syntax ()*.
.IP nomatch
The nomatch regular expression represents the
empty set: it matches no strings at all, not even the empty string.
There is no dedicated syntax to directly express nomatch in the regex language.
However, the empty character class [] is equivalent to nomatch, and may be
considered to be a notation for it. Other representations of nomatch are
possible: for instance, the regex ~.* which is the complement of the regex that
denotes the set of all possible strings, and thus denotes the empty set. A
nomatch has uses; for instance, it can be used to temporarily "comment out"
regular expressions. The regex ([]abc|xyz) is equivalent to (xyz), since the
[]abc branch cannot match anything. Using [] to "block" a subexpression allows
you to leave it in place, then enable it later by removing the "block".
.IP (R)
If R is a regular expression, then so is (R).
The contents of parentheses denote one regular expression unit, so that for
instance in (RE)*, the * operator applies to the entire parenthesized group.
The syntax () is valid and equivalent to the empty regular expression.
.IP R?
optionally match the preceding regular expression R.
.IP R*
match the expression R zero or more times. This
operator is sometimes called the "Kleene star", or "Kleene closure".
The Kleene closure favors the longest match. Roughly speaking, if there are two
or more ways in which R1*R2 can match, than that match occurs in which
R1* matches the longest possible text.
.IP R+
match the preceding expression R one or more times.
Like R*, this favors the longest possible match: R+ is equivalent to RR*.
.IP R1%R2
match R1 zero or more times, then match R2. If this match can occur in
more than one way, then it occurs such that R1 is matched the fewest
number of times, which is opposite from the behavior of R1*R2.
Repetitions of R1 terminate at the earliest
point in the text where a non-empty match for R2 occurs. Because
it favors shorter matches, % is termed a non-greedy operator.  If R2 is the
empty expression, or equivalent to it, then R1%R2 reduces to R1*.  So for
instance (R%) is equivalent to (R*), since the missing right operand is
interpreted as the empty regex. Note that whereas the expression
(R1*R2) is equivalent to (R1*)R2, the expression (R1%R2) is 
.B not
equivalent to (R1%)R2.
.IP ~R
match the opposite of the following expression R; i.e. match exactly
those texts that R does not match. This operator is called complement,
or logical not.
.IP R1R2
Two consecutive regular expressions denote catenation:
the left expression must match, and then the right.
.IP R1|R2
match either the expression R1 or R2. This operator is known by
a number of names: union, logical or, disjunction, branch, or alternative.
.IP R1&R2
match both the expression R1 and R2 simultaneously; i.e. the
matching text must be one of the texts which are in the intersection of the set
of texts matched by R1 and the set matched by R2. This operator is called
intersection, logical and, or conjunction.

.PP
Any escaped character which does not fall into the above escaping conventions,
or any unescaped character which is not a regular expression operator, denotes
one-position match of that character itself.

Any of the special characters, including the delimiting /,  can be escaped with
a backslash to suppress its meaning and denote the character itself.

Furthermore, all of the same escapes as are described in the section Special
Characters in Text above are supported---the difference is that in regular
expressions, the @ character is not required, so for example a tab is coded as
\et rather than @\e\t. Octal and hex character escapes can be optionally
terminated by a semicolon, which is useful if the following characters are
octal or hex digits not intended to be part of the escape.

Precedence table, highest to lowest:
.TS
tab(!);
l l l.
operators!class!associativity
(R) []!primary!
R? R+ R* R%...!postfix!left-to-right
R1R2!catenation!left-to-right
~R ...%R!unary!right-to-left
R1&R2!intersection!left-to-right
R1|R2!union!left-to-right
.TE

The % operator is like a postfix operator with respect to its left
operand, but like a unary operator with respect to its right operand.
Thus a~b%c~d  is a(~(b%(c(~d)))), demonstrating right-to-left associativity,
where all of b% may be regarded as a unary operator being applied to c~d. 
Similarly, a?*+%b  means (((a?)*)+)%b, where the trailing %b behaves
like a postfix operator.

In
.B TXR,
regular expression matches do not span multiple lines. The regex language has
no feature for multi-line matching. However, the @(freeform) directive
allows the remaining portion of the input to be treated as one string
in which line terminators appear as explicit characters. Regular expressions
may freely match through this sequence.

It's possible for a regular expression to match an empty string.
For instance, if the next input character is z, facing a
the regular expression /a?/, there is a zero-character match:
the regular expression's state machine can reach an acceptance
state without consuming any characters. Examples:

  pattern:      @A@/a?/@/.*/
  data:         zzzzz
  result:       A=""

  pattern:      @{A /a?/}@B
  data:         zzzzz
  result:       A="", B="zzzz"

  pattern:      @*A@/a?/
  data:         zzzzz
  result:       A="zzzzz"

In the first example, variable @A is followed by a regular expression
which can match an empty string. The expression faces the letter "z"
at position 0 in the data line. A zero-character match occurs there,
therefore the variable A takes on the empty string. The @/.*/ regular
expression then consumes the line.

Similarly, in the second example, the /a?/ regular expression faces
a "z", and thus yields an empty string which is bound to A. Variable
@B consumes the entire line.

The third example requests the longest match for the variable binding.
Thus, a search takes place for the rightmost position where the
regular expression matches. The regular expression matches anywhere,
including the empty string after the last character, which is
the rightmost place. Thus variable A fetches the entire line.

For additional information about the advanced regular expression
operators, NOTES ON EXOTIC REGULAR EXPRESSIONS below.

.SS Directives

The general syntax of a directive is:

  @EXPR

where expr is a parenthesized list of subexpressions. A subexpression
is an symbol, number, string literal, character literal, quasiliteral, regular
expression, or a parenthesized expression.  So, examples of syntactically valid
directives are:

  @(banana)

  @(a b c (d e f))

  @(  a (b (c d) (e  ) ))

  @("apple" #\eb #\espace 3)

  @(a /[a-z]*/ b)

  @(_ `@file.txt`)

A symbol is lexically the same thing as a variable name (the type enclosed
in braces in the @{NAME} syntax) and the same rules apply: it can consist
of all the same characters, and must not look like a number. Tokens that look
like numbers are treated as numbers.

.SS Special Symbols

Just like in the programming language Lisp, the names nil and t cannot be used
as variables. They always represent themselves, and have many uses, internal to
the program as well as externally visible. The nil symbol stands for the empty
list object, an object which marks the end of a list, and boolean false. It is
synonymous with the syntax () which may be used interchangeably with nil in
most constructs.

.SS Keyword Symbols

Names whose names begin with the : character are keyword symbols.  These also
may not be used as variables either and stand for themselves. Keywords are
useful for labeling information and situations. 

.SS Character Literals

Character literals are introduced by the #\e syntax, which is either
followed by a character name, the letter x followed by hex digits,
the letter o followed by octal digits, or a single character. Valid character
names are: nul, alarm, backspace, tab, linefeed, newline, vtab, page, return,
esc, space. This convention for character literals is similar to that of the
Scheme language.  Note that #\elinefeed and #\enewline are the same character.

.SS String Literals

String literals are delimited by double respectively, and may not span multiple
lines. A double quote within a string literal is encoded using \e"
and a backslash is encoded as \e\e. Backslash escapes like \en and \et
are recognized, as are hexadecimal escapes like \exFF or \exxabc and octal
escapes like \e123.  Ambiguity between an escape and subsequent
text can be resolved by using trailing semicolon delimiter: "\exabc;d" is a
string consisting of the character U+0ABC followed by "d". The semicolon
delimiter disappears. To write a literal semicolon immediately after a hex
or octal escape, write two semicolons, the first of which will be interpreted
as a delimiter. Thus, "\ex21;;" represents "!;".

.SS String Quasiliterals

Quasiliterals are similar to string literals, except that they may
contain variable references denoted by the usual @ syntax. The quasiliteral
represents a string formed by substituting the values of those variables
into the literal template. If a is bound to "apple" and b to "banana",
the quasiliteral `one@a and two @{b}s` represents the string
"one apple and two bananas". A backquote escaped by a backslash represents
itself, and two consecutive @ characters code for a literal @.
There is no \e@ escape.  Quasiliterals support the full output variable
syntax. Expressions within variables substitutions follow the evaluation rules
of TXR Lisp when the quasiliteral occurs in TXR Lisp, and the rules of
the TXR pattern language when the quasiliteral occurs in the pattern language.

.SS Numbers

TXR supports integers and floating-point numbers. 

An integer constant is made up of digits 0 through 9, optionally preceded by a
+ or - sign.

Examples:

  123
  -34
  +0
  -0
  +234483527304983792384729384723234

An integer constant can also be specified in hexadecimal using the prefix
#x followed by an optional sign, followed by hexadecimal digits: 0 through 9
and the upper or lower case letters A through F:

  #xFF    ;; 255
  #x-ABC  ;; -2748

A floating-point constant is marked by the inclusion of a decimal point, the
exponential "e notation", or both. It is an optional sign, followed
by a mantissa consisting of digits, a decimal point, more digits, and then an
optional exponential notation consisting of the letter "e" or "E", an optional
"+" or "-" sign, and then digits indicating the exponent value.
In the mantissa, the digits are not optional. At least one digit must either
precede the decimal point or follow. That is to say, a decimal point by itself
is not a floating-point constant.

Examples:

  .123
  123.
  1E-3
  20E40
  .9E1
  9.E19
  -.5
  +3E+3

Examples which are not floating-point constant tokens:

  .       (consing dot)
  123E    (the symbol 123E)
  1.0E-   (floating point 1.0 followed by symbol E-)
  .e      (consing dot followed by symbol e)

In TXR there is a special "dotdot" token consisting of two consecutive periods.
An integer constant followed immediately by dotdot is recognized as such; it is
not treated as a floating constant followed by a dot. That is to say,
123.. does not mean 123. . (floating point 123.0 value followed by dot token).
It means 123 .. (integer 123 followed by .. token).

Dialect note: unlike in Common Lisp, 123. is not an integer, but the same as
123.0.

.SS Comments

Comments of the form @; were already covered. Inside directives,
comments are introduced just by a ; character.

Example:

  @(foo  ; this is a comment
    bar  ; this is another comment 
    )

This is equivalent to @(foo bar).

.SS Directives-driven Syntax

Some directives not only denote an expression, but are also involved in
surrounding syntax. For instance, the directive

  @(collect)

not only denotes an expression, but it also introduces a syntactic phrase which
requires a matching @(end) directive. So in other words, @(collect) is not only
an expression, but serves as a kind of token in a higher level phrase structure
grammar.

Usually if this type of "syntactic directive" occurs alone in a line, not
preceded or followed by other material, it is involved in a "vertical" (or line
oriented) syntax.

If such a directive is embedded in a line (has preceding or trailing material)
then it is in a horizontal syntactic and semantic context (character-oriented).

There is an exception: the a definition of a horizontal function
looks like this:

  @(define name (arg))body material@(end)

Yet, this is considered one vertical item, which means that it does not match
a line of data. (This is necessary because all horizontal syntax matches
something within a line of data.)

Many directives have a horizontal and vertical syntax, with different but
closely related semantics. A few are still "vertical only", and some are
horizontal only but in future releases, these exceptions will be minimized.

A summary of the available directives follows:

.IP @(eof)
Explicitly match the end of file. Fails if unmatched data remains in
the input stream.

.IP @(eol)
Explicitly match the end of line. Fails if the the current position is not the
end of a line. Also Fails if no data remains (there is no current line).

.IP @(next)
Continue matching in another file or other data source.

.IP @(block)
Groups to gether a sequence of directives into a logical name block,
which can be explicitly terminated from within using
the @(accept) and @(fail) directives.
Blocks are discussed in the section BLOCKS below.

.IP @(skip)
Treat the remaining query as a subquery unit, and search the lines (or
characters) of the input file until that subquery matches somewhere.  A skip is
also an anonymous block.

.IP @(trailer)
Treat the remaining query or subquery as a match for a trailing context. That
is to say, if the remainder matches, the data position is not advanced.

.IP @(freeform)
Treat the remainder of the input as one big string, and apply the following
query line to that string. The newline characters (or custom separators) appear
explicitly in that string.

.IP @(fuzz)
The fuzz directive, inspired by the patch utility, specifies a partial
match for some lines.

.IP @(some)
Multiple clauses are each applied to the same input. Succeeds if at least one
of the clauses matches the input. The bindings established by earlier
successful clauses are visible to the later clauses.

.IP @(all)
Multiple clauses are applied to the same input. Succeeds if and only if each
one of the clauses matches. The clauses are applied in sequence, and evaluation stops on the first failure.  The bindings established by earlier
successful clauses are visible to the later clauses.

.IP @(none)
Multiple clauses are applied to the same input. Succeeds if and only if none of
them match. The clauses are applied in sequence, and evaluation stops on the
first success. No bindings are ever produced by this construct.

.IP @(maybe)
Multiple clauses are applied to the same input. No failure occurs if none of
them match.  The bindings established by earlier successful clauses are visible
to the later clauses.

.IP @(cases)
Multiple clauses are applied to the same input. Evaluation stops on the
first successful clause.

.IP @(choose)
Multiple clauses are applied to the same input. The one whose effect persists
is the one which maximizes or minimizes the length of a particular variable.

.IP "@(define NAME ( ARGUMENTS ...))"
Introduces a function. Functions are discussed in the FUNCTIONS section below.

.IP @(gather)
Searches text for matches for multiple clauses which may occur in arbitrary
order. For convenience, lines of the first clause are treated as separate
clauses.

.IP @(collect)
Search the data for multiple matches of a clause. Collect the
bindings in the clause into lists, which are output as array variables.
The @(collect) directive is line oriented. It works with a multi-line
pattern and scans line by line. A similar directive called @(coll)
works within one line.

A collect is an anonymous block.

.IP @(and)
Separator of clauses for @(some), @(all), @(none), @(maybe) and @(cases).
Equivalent to @(or). Choice is stylistic.

.IP @(or)
Separator of clauses for @(some), @(all), @(none), @(maybe) and @(cases).
Equivalent to @(and). Choice is stylistic.

.IP @(end)
Required terminator for @(some), @(all), @(none), @(maybe), @(cases),
@(collect), @(coll), @(output), and @(repeat).

.IP @(fail)
Terminate the processing of a block, as if it were a failed match.
Blocks are discussed in the section BLOCKS below.

.IP @(accept)
Terminate the processing of a block, as if it were a successful match.
What bindings emerge may depend on the kind of block: collect
has special semantics.  Blocks are discussed in the section BLOCKS below.

.IP @(try)
Indicates the start of a try block, which is related to exception
handling, discussed in the EXCEPTIONS section below.

.IP "@(catch), @(finally)"
Special clauses within @(try). See EXCEPTIONS below.

.IP "@(defex), @(throw)"
Define custom exception types; throw an exception.  See EXCEPTIONS below.

.IP @(flatten)
Normalizes a set of specified variables to one-dimensional lists. Those
variables which have scalar value are reduced to lists of that value.
Those which are lists of lists (to an arbitrary level of nesting) are converted
to flat lists of their leaf values.

.IP @(merge)
Binds a new variable which is the result of merging two or more
other variables. Merging has somewhat complicated semantics.

.IP @(cat)
Decimates a list (any number of dimensions) to a string, by catenating its
constituent strings, with an optional separator string between all of the
values.

.IP @(bind)
Binds one or more variables against a value using a structural
pattern match. A limited form of unification takes place which can cause a
match to fail.

.IP @(set)
Destructively assigns one or more existing variables using a structural
pattern, using syntax similar to bind. Assignment to unbound
variables triggers an error.

.IP @(rebind)
Evaluates an expression in the current binding environment, and
then creates new bindings for the variables in the structural pattern.
Useful for temporarily overriding variable values in a scope.

.IP @(output)
A directive which encloses an output clause in the query. An output section
does not match text, but produces text. The directives above are not
understood in an output clause.

.IP @(repeat)
A directive understood within an @(output) section, for repeating multi-line
text, with successive substitutions pulled from lists. The directive @(rep)
produces iteration over lists horizontally within one line.

.IP @(deffilter)
This directive is used for defining named filters, which are useful
for filtering variable substitutions in output blocks. Filters are useful
when data must be translated between different representations that
have different special characters or other syntax, requiring escaping
or similar treatment. Note that it is also possible to use a function
as a filter. See Function Filters below.

.IP @(filter)
The filter directive passes one or more variables through a given
filter or chain or filters, updating them with the filtered values.

.IP @(load)
The load directive loads another TXR file and interprets its contents.

.PP

.SH INPUT SCANNING AND DATA MANIPULATION

.SS The Next Directive

The next directive indicates that the remainder of the query is to be applied
to a new input source.

It can only occur by itself as the only element in a query line,
and takes various arguments, according to these possiblities:

  @(next)
  @(next SOURCE)
  @(next SOURCE :nothrow)
  @(next :args)
  @(next :env)
  @(next :list EXPR)
  @(next :string EXPR)

The lone @(next) without arguments switches to the next file in the
argument list which was passed to the
.B TXR
utility. However, "switch to the next file" means in a pattern matching
way, not in an imperative way. It is possible for the pattern matching
logic to implicitly backtrack to the previous file.

If SOURCE is given, it must be text-valued expression which denotes an
input source; it may be a string literal, quasiliteral or a variable.
For instance, if variable A contains the text "data", then

  @(next A)

means switch to the file called "data", and

  @(next `@A.txt`)

means to switch to the file "data.txt".

If the input source cannot be opened for whatever reason,
.B TXR
throws an exception (see EXCEPTIONS below). An unhandled exception will
terminate the program.  Often, such a drastic measure is inconvenient;
if @(next) is invoked with the :nothrow keyword, then if the input
source cannot be opened, the situation is treated as a simple
match failure.

The variant @(next :args) means that the remaining command line arguments are to
be treated as a data source. For this purpose, each argument is considered to
be a line of text. If an argument is currently being processed as an input
source, that argument is included. Note that if the first entry in the argument
list is not intended to name an input source, then the query should begin with
@(next :args) or some other form of next directive, to prevent an attempt to
open the input source named by that argument. If the very first directive of a query is any variant of the next directive, then
.B TXR
avoids opening the first input source, but it does open the input source for
any other directive, even one which does not consume any data.

The variant @(next :env) means that the list of process environment variables
is treated as a source of data. It looks like a text file stream
consisting of lines of the form "name=value".  If this feature is not available
on a given platform, an exception is thrown.

The syntax @(next :list EXPR) treats the expression as a source of
text. The value of the expression is flattened to a list in a way similar
to the @(flatten) directive.  The resulting list is treated as if it were the
lines of a text file: each element of the list is a line. If the lines
happen contain embedded newline characters, they are a visible constituent
of the line, and do not act as line separators.

The syntax @(next :string EXPR) treats the expression as a source of
text. The value of the expression must be a string. Newlines in the string are
interpreted as line terminators. 

A string which is not terminated by
a newline is tolerated, so that:

  @(next :string "abc")
  @a

binds a to "abc".  Likewise, this is also the case with input files and other
streams whose last line is not terminated by a newline.

However, watch out for empty strings, which are analogous to a correctly formed
empty file which contains no lines:

  @(next :string "")
  @a

This will not bind a to ""; it is a matching failure.  The behavior of :list is
different. The query

  @(next :list "")
  @a

binds a to "".  The reason is that under :list the string "" is flattened to
the list ("") which is not an empty input stream, but a stream consisting of
one empty line.

Note that "remainder of the query" which is applied to the stream opened
by @(next) refers to the subquery in which the next directive appears, not
necessarily the entire query.  For example, the following query looks for the
line starting with "xyz" at the top of the file "foo.txt", within a some
directive.  After the @(end) which terminates the @(some), the "abc" is matched
in the previous file again.

  @(some)
  @(next "foo.txt")
  xyz@suffix
  @(end) abc

However, if the @(some) subquery successfully matched "xyz@suffix" within the
file foo.text,  there is now a binding for the suffix variable, which
is visible to the remainder of the entire query. The variable bindings
survive beyond the clause, but the data stream does not.

The @(next) directive supports the file name conventions as the command
line. The name - means standard input. Text which starts with a ! is
interpreted as a shell command whose output is read like a file.  These
interpretations are applied after variable substitution. If the file is
specified as @a, but the variable a expands to "!echo foo", then the output of
the "echo foo" command will be processed.

.SS The Skip Directive

The skip directive considers the remainder of the query as a search
pattern. The remainder is no longer required to strictly match at the
current line in the current file. Rather, the current file is searched,
starting with the current line, for the first line where the entire remainder
of the query will successfully match. If no such line is found, the skip
directive fails. If a matching position is found, the remainder of
the query is understood to be processed there.

Of course, the remainder of the query can itself contain skip directives.
Each such directive performs a recursive subsearch.

Skip comes in vertical and horizontal flavors. For instance, skip and match the
last line:

  @(skip)
  @last
  @(eof)

Skip and match the last character of the line:

  @(skip)@{last 1}@(eol)

The skip directive has two optional arguments. If the first argument is a
number, its value limits the range of lines scanned for a match. Judicious use
of this feature can improve the performance of queries.

Example: scan until "size: @SIZE" matches, which must happen within
the next 15 lines:

  @(skip 15)
  size: @SIZE

Without the range limitation skip will keep searching until it consumes
the entire input source. While sometimes this is what is intended,
often it is not. Sometimes a skip is nested within a collect, or
following another skip. For instance, consider:

  @(collect)
  begin @BEG_SYMBOL
  @(skip)
  end @BEG_SYMBOL
  @(end)

The collect iterates over the entire input. But, potentially, so does
the skip. Suppose that "begin x" is matched, but the data has no
matching "end x". The skip will search in vain all the way to the end of the
data, and then the collect will try another iteration back at the
beginning, just one line down from the original starting point.  If it is a
reasonable expectation that an "end x" occurs 15 lines of a "begin x", this can
be written instead:

  @(collect)
  begin @BEG_SYMBOL
  @(skip 15)
  end @BEG_SYMBOL
  @(end)

If the symbol nil is used in place of a number, it means to scan
an unlimited range of lines; thus, @(skip nil) is equivalent to @(skip).

If the symbol :greedy is used, it changes the semantics of the skip
to longest match semantics, like the regular expression * operator.
For instance, match the last three space-separated tokens of the line:

  @(skip :greedy) @a @b @c

Without :greedy, the variable @c will can match multiple tokens,
and end up with spaces in it, because nothing follows @c and
so it matches from any position which follows a space to the
end of the line.  Also note the space in front of @a. Without this
space, @a will get an empty string.

A line oriented example of greedy skip: match the last line without
using @eof:

  @(skip :greedy)
  @last_line

There may be a second numeric argument. This specifies a minimum
number of lines to skip before looking for a match. For instance,
skip 15 lines and then search indefinitely for "begin ...":

  @(skip nil 15)
  begin @BEG_SYMBOL

The two arguments may be used together. For instance, the following
matches if, and only if, the 15th line of input starts with "begin ":

  @(skip 1 15)
  begin @BEG_SYMBOL

Essentially, @(skip 1 <n>) means "hard skip by <n>" lines, then
match the query without scanning.  @(skip 1 0) is the same as @(skip 1), which
is a noop, because it means: "the remainder of the query must match starting on
the very next line", or, more briefly, "skip exactly zero lines", which is the
behavior if the skip directive is omitted altogether.

Here is one trick for grabbing the fourth line from the bottom of the input:

  @(skip)
  @fourth_from_bottom
  @(skip 1 3)
  @(eof)

Or using greedy skip:

  @(skip :greedy)
  @fourth_from_bottom
  @(skip 1 3)

Nongreedy skip with the @(eof) has a slight advantage because the greedy skip
will keep scanning even though it has found the correct match, then backtrack
to the last good match once it runs out of data. The regular skip with explicit
@(eof) will stop when the @(eof) matches.

.SS Reducing Backtracking with Blocks

Skip can consider considerable CPU time when multiple skips are nested.
Consider:

  @(skip)
  A
  @(skip)
  B
  @(skip)
  C

This is actually nesting: the second a third skips occur within the body of the
first one, and thus this creates nested iteration. TXR is searching for the
combination of skips which find match the pattern of lines A, B and C, with
backtracking behavior. The outermost skip marches through the data until it
finds A, followed by a pattern match for the second skip. The second skip
iterates within to find B, followed by the third skip, and the third skip
iterates to find C. If there is only one line A, and one B, then this is
reasonably fast. But suppose there are many lines matching A and B,
giving rise to a large number combinations of skips which match A and B, and
yet no match for C, triggering backtracking. The nested stepping which tries
the combinations of A and B can give rise to a considerable running time.

One way to deal with the problem is to unravel the nesting with the help of
blocks. For example:

  @(block)
  @  (skip)
  A
  @(end)
  @(block)
  @  (skip)
  B
  @(end)
  @(skip)
  C

Now the scope of each skip is just the remainder of the block in which it
occurs. The first skip finds A, and then the block ends. Control passes to the
next block, and backtracking will not take place to a block which completed
(unless all these blocks are enclosed in some larger construct which
backtracks, causing the blocks to be re-executed.

Of course, this rewrite is not equivalent, and cannot be used for instance
in backreferencing situations such as:

  @;
  @; Find some three lines which are the same.
  @;
  @(skip)
  @line
  @(skip)
  @line
  @(skip)
  @line

This example depends on the nested search-within-search semantics.

.SS The Trailer Directive

The trailer directive introduces a trailing portion of a query or subquery
which matches input material normally, but in the event of a successful match,
does not advance the current position. This can be used, for instance, to
cause @(collect) to match partially overlapping regions.

Example:

  @(collect)
  @line
  @(trailer)
  @(skip)
  @line
  @(end)

This script collects each line which has a duplicate somewhere later
in the input. Without the @(trailer) directive, this does not work properly
for inputs like:

  111
  222
  111
  222

Without @(trailer), the first duplicate pair constitutes a match which
spans over the 222. After that pair is found, the matching continues
after the second 111.

With the @(trailer) directive in place, the collect body, on each
iteration, only consumes the lines matched prior to @(trailer).

.SS The Freeform Directive

The freeform directive provides a useful alternative to
.B TXR's
line-oriented matching discipline. The freeform directive treats all remaining
input from the current input source as one big line. The query line which
immediately follows freeform is applied to that line.

The syntax variations are:

  @(freeform)
  ... query line ..

  @(freeform NUMBER)
  ... query line ..

  @(freeform STRING)
  ... query line ..

  @(freeform NUMBER STRING)
  ... query line ..

The string and numeric arguments, if both are present, may be given in either
order.

If a numeric argument is given, it limits the range of lines which are combined
together. For instance @(freeform 5) means to only consider the next five lines
to to be one big line. Without a numeric argument, freeform is "bottomless". It
can match the entire file, which creates the risk of allocating a large amount
of memory.

If a string argument is given, it specifies a custom line terminator. The
default terminator is "\en". The terminator does not have to be one character
long.

Freeform does not convert the entire remainder of the input into one big line
all at once, but does so in a dynamic, lazy fashion, which takes place as the
data is accessed. So at any time, only some prefix of the data exists as a flat
line in which newlines are replaced by the terminator string, and the remainder
of the data still remains as a list of lines.

After the subquery is applied to the virtual line, the unmatched remainder
of that line is broken up into multiple lines again, by looking for and
removing all occurences of the terminator string within the flattened portion.

Care must be taken if the terminator is other than the default "\en". All
occurences of the terminator string are treated as line terminators in
the flattened portion of the data, so extra line breaks may be introduced.
Likewise, in the yet unflattened portion, no breaking takes place, even if
the text contains occurences of the terminator string. The extent of data which
is flattened, and the amount of it which remains, depends entirely on the
query line underneath @(flatten).

In the following example, lines of data are flattened using $ as the line
terminator.

  Query:        @(freeform "$")
                @a$@b:
                @c
                @d

  Data:         1
                2:3
                4

  Output:       a="1"
                b="2"
                c="3"
                d="4"

The data is turned into the virtual line 1$2:3$4$.  The @a$@b: subquery matches
the 1$2: portion, binding a to 1, and b to 2.  The remaining portion 3$4$ is
then split into separate lines again according to the line terminator $:

                3
                4

Thus the remainder of the query

                @c
                @d

faces these lines, binding c to 3 and d to 4. Note that since the data
does not contain dollar signs, there is no ambiguity; the meaning may be
understood in terms of the entire data being flattened and split again.

In the following example, freeform is used to solve a tokenizing problem.  The
Unix password file has fields separated by colons. Some fields may be empty.
Using freeform, we can join the password file using ":" as a terminator.
By restricting freeform to one line, we can obtain each line of the password
file with a terminating ":", allowing for a simple tokenization, because
now the fields are colon-terminated rather than colon-separated.

Example:

  @(next "/etc/passwd")
  @(collect)
  @(freeform 1 ":")
  @(coll)@{token /[^:]*/}:@(end)
  @(end)

.SS The Fuzz Directive

The fuzz directive allows for an imperfect match spanning a set number of
lines. It takes two arguments, both expressions that should evaluate
to integers:

  @(fuzz m n)
  ...

This expresses that over the next n query lines, the matching strictness
is relaxed a little bit. Only m out of those n lines have to match.
Afterward, the rest of the query follows normal, strict processing.

In the degenerate situation that there are fewer than n query lines following
the fuzz directive, then m of them must succeed nevertheless. (If there
are fewer than m, then this is impossible.)

.SS The Some, All, None, Maybe, Cases and Choose directives

These directives, called the parallel directives, combine multiple subqueries,
which are applied at the same input position, rather than to consecutive input.

They come in vertical (line mode) and horizontal (character mode) flavors.

In horizontal mode, the current position is understood to be a character
position in the line being processed. The clauses advance this character
position by moving it to the right.  In vertical mode, the current position is
understood to be a line of text within the stream. A clause advances the
position by some whole number of lines.

The syntax of these parallel directives follows this example:

  @(some)
  subquery1
  .
  .
  .
  @(and)
  subquery2
  .
  .
  .
  @(and)
  subquery3
  .
  .
  .
  @(end)

And in horizontal mode:

  @(some)subquery1...@(and)subquery2...@(and)subquery3...@(end)

Long horizontal lines can be broken up with line continuations, allowing the
above example to be written like this, which is considered a single logical
line:

  @(some)@\
     subquery1...@\
  @(and)@\
     subquery2...@\
  @(and)@\
     subquery3...@\
  @(end)

The @(some), @(all), @(none), @(maybe), @(cases) or @(choose) must be followed
by at least one subquery clause, and be terminated by @(end). If there are two
or more subqueries, these additional clauses are indicated by @(and) or @(or),
which are interchangeable.  The separator and terminator directives also must
appear as the only element in a query line.

The choose directive requires keyword arguments. See below.

The syntax supports arbitrary nesting. For example:

  QUERY:            SYNTAX TREE:

  @(all)            all -+
  @  (skip)              +- skip -+
  @  (some)              |        +- some -+
  it                     |        |        +- TEXT
  @  (and)               |        |        +- and
  @    (none)            |        |        +- none -+
  was                    |        |        |        +- TEXT
  @    (end)             |        |        |        +- end
  @  (end)               |        |        +- end
  a dark                 |        +- TEXT
  @(end)                 *- end

nesting can be indicated using whitespace between @ and the
directive expression. Thus, the above is an @(all) query containing a @(skip)
clause which applies to a @(some) that is followed by the the text
line "a dark". The @(some) clause combines the text line "it",
and a @(none) clause which contains just one clause consisting of
the line "was".

The semantics of the parallel directives is:

.IP @(all)
Each of the clauses is matched at the current position. If any of the
clauses fails to match, the directive fails (and thus does not produce
any variable bindings). Clauses following the failed directive are not
evaluated. Bindings extracted by a successful clause are visible the clauses
which follow, and if the directive succeeds, all of the combined bindings
emerge.

.IP "@(some [ :resolve (vars ...) ])"
Each of the clauses is matched at the current position. If any of the clauses
succeed, the directive succeeds, retaining the bindings accumulated by the
successully matching clauses.  Evaluation does not stop on the first successful
clause. Bindings extracted by a successful clause are visible to the clauses
which follow.

The :resolve parameter is for situations when the @(some) directive has
multiple clauses that need to bind some common variables to different
values: for instance, output parameters in functions. Resolve takes
a list of variable name symbols as an argument.  This is called the
resolve set. If the clauses of @(some) bind variables in the resolve
set, those bindings are not visible to later clauses.  However, those
bindings do emerge out of the @(some) directive as a whole.
This creates a conflict: what if two or more clauses introduce
non-matching bindings for a variable in the resolve set?
This is why it is called the resolve set: conflicts for variables in the
resolve set are automatically resolved in favor of later directives.

Example:

  @(some :resolve (x))
  @  (bind a "a")
  @  (bind x "x1")
  @(or)
  @  (bind b "b")
  @  (bind x "x2")
  @(end)

Here, the two clauses both introduce a binding for x.  Without the :resolve
parameter, this would mean that the second clause fails, because x comes in
with the value "x1", which does not bind with "x2".  But because x is placed
into the resolve set, the second clause does not see the "x1" binding. Both
clauses establish their bindings independently creating a conflict over x.
The conflict is resolved in favor of the second clause, and so the bindings
which emerge from the directive are:

  a="a"
  b="b"
  x="x2"

.IP @(none)
Each of the clauses is matched at the current position. The
directive succeeds only if all of the clauses fail. If
any clause succeeds, the directive fails, and subsequent clauses are not
evaluated. Thus, this directive never produces variable bindings, only matching
success or failure.

.IP @(maybe)
Each of the clauses is matched at the current position.  The directive always
succeeds, even if all of the clauses fail.  Whatever bindings are found in any
of the clauses are retained. Bindings extracted by any successful clause are
visible the clauses which follow.

.IP @(cases)
Each of the clauses is matched at the current position. The
The clauses are matched, in order, at the current position.
If any clause matches, the matching stops and the bindings
collected from that clause are retained. Any remaining clauses
after that one are not processed. If no clause matches, the
directive fails, and produces no bindings.

.IP "@(choose [ :longest <var> | :shortest <var> ])"
Each of the clauses is matched at the current position in order. In this
construct, bindings established an earlier clause are not visible to later
clauses.  Although any or all of the clauses can potentially match, the clause
which succeeds is the one which maximizes or minimizes the length of the
text bound to the specified variable. The other clauses have no effect.

For all of the parallel directives other than @(none) and @(choose), the query
advances the input position by the greatest number of lines that match in any
of the successfully matching subclauses that are evaluated.  The @(none)
directive does not advance the input position.

For instance if there are two subclauses, and one of them matches three lines,
but the other one matches five lines, then the overall clause is considered to
have made a five line match at its position. If more directives follow, they
begin matching five lines down from that position.

.SS The Gather Directive

Sometimes text is structured as items that can appear in an arbitrary order.
When multiple matches need to be extracted, there is a combinatorial explosion
of possible orders, making it impractical to write pattern matches for all
the possible orders.

The gather directive is for these situations. It specifies multiple clauses
which all have to match somewhere in the data, but in any order.

For further convenience, the lines of the first clause of the gather directive
are implicitly treated as separate clauses.

The syntax follows this pattern

  @(gather)
  one-line-query1
  one-line-query2
  .
  .
  .
  one-line-queryN
  @(and)
  multi
  line
  query1
  .
  .
  .
  @(and)
  multi
  line
  query2
  .
  .
  .
  @(end)

Of course the multi-line clauses are optional.   The gather directive takes
keyword parameters, see below.

Similarly to @(collect), @(gather) has an optional until/last clause:

  @(gather)
  ...
  @(until)
  ...
  @(end)

How gather works is that the text is searched for matches for the single line
and multi-line queries. The clauses are applied in the order in which they appear.
Whenever one of the clauses matches, any bindings it produces are retained and
it is removed from further consideration. Multiple clauses can match at the
same text position.  The position advances by the longest match from among the
clauses which matched.  If no clauses match, the position advances by one line.
The search stops when all clauses are eliminated, and then the cumulative
bindings are produced.  If the data runs out, but unmatched clauses remain, the
directive fails.

Example: extract several environment variables, which do not appear in a particular
order:

  @(next :env)
  @(gather)
  USER=@USER
  HOME=@HOME
  SHELL=@SHELL
  @(end)

If the until or last clause is present and a match occurs, then the matches
from the other clauses are discarded and the gather terminates. The difference
between until and last is that any bindings bindings established in last are
retained, and the input position is advanced past the matched material.
The until/last clause has visibility to bindings established in the
previous clauses in that same iteration, even though those bindings
end up thrown away.

.SS Gather Keyword Parameters

The gather diretive accepts the keyword parameter :vars. The argument to vars is a list
of required and optional variables.  Optional variables are denoted by the
specification of a default value. Example:

  @(gather :vars (a b c (d "foo")))
  ...
  @(end)

Here, a, b, c and e are required variables, and d is optional.  Variable e is
required because its default value is the empty list (), same as the symbol
nil. 

The presence of vars changes the behavior in three ways.

Firstly, even if all the clauses in the gather match successfully and are
eliminated, the directive will fail if the required variables do not have
bindings. It doesn't matter whether the bindings are existing, or whether they
are established by the gather.

Secondly, if some of the clauses of the gather did not match, but all
of the required variables have bindings, then the directive succeeds.
Without the presence of :vars, it would fail in this situation.

Thirdly, if the the gather succeeds (all required variables have bindings),
then all of the optional variables which do not have bindings are given
bindings to their default values.

.SS The Collect Directive

The syntax of the collect directive is:

  @(collect)
  ... lines of subquery
  @(end)

or with an until or last clause:

  @(collect)
  ... lines of subquery: main clause
  @(until)
  ... lines of subquery: until clause
  @(end)

  @(collect)
  ... lines of subquery: main clause
  @(last)
  ... lines of subquery: last clause
  @(end)

The repeat symbol may be specified instead of collect, which changes
the meaning, see below:

  @(repeat)
  ... lines of subquery
  @(end)

The subquery is matched repeatedly, starting at the current line.
If it fails to match, it is tried starting at the subsequent line.
If it matches successfully, it is tried at the line following the
entire extent of matched data, if there is one. Thus, the collected regions do
not overlap. (Overlapping behavior can be obtained: see the
@(trailer) directive).

Unless certain keywords are specified, or unless the collect is explicitly
failed with @(fail), it always succeeds, even if it collects nothing,
and even if the until/last clause never finds a match.

If no until/last clause is specified, and the collect is not limited
using parameters, the collect is unbounded. It consumes the entire data
file. If any query material follows such the collect clause, it will fail if it
tries to match anything in the current file; but of course, it is possible to
continue matching in another file by means of @(next).

If an until/last clause is specified, the collection stops when that clause
matches at the current position. 

If an until clause terminates collect, no bindings are collected at that
position, even if the main clause matches at that position also. Moreover, the
position is not advanced.  The remainder of the query begins matching at that
position.  

If a last clause terminates collect, the behavior is different. Any bindings
captured by the main clause are thrown away, just like with the until clause.
However, the bindings in the last clause itself survive, and the position is
advanced to skip over that material.

Example:

  Query:        @(collect)
                @a
                @(until)
                42
                @b
                @(end)
                @c

  Data:         1
                2
                3
                42
                5
                6

  Output:       a[0]="1"
                a[1]="2"
                a[2]="3"
                c="42"

The line 42 is not collected, even though it matches @a. Furthermore,
the until does not advance the position, so variable c takes 42.

If the @(until) is changed to @(last) the output will be different:

  Output:       a[0]="1"
                a[1]="2"
                a[2]="3"
                b=5
                c=6

The 42 is not collected into the a list, just like before. But now
the binding captured by @b emerges. Furthermore, the position advances
so variable now takes 6.

The binding variables within the clause of a collect are treated specially.
The multiple matches for each variable are collected into lists,
which then appear as array variables in the final output.

Example:

  Query:        @(collect)
                @a:@b:@c
                @(end)

  Data:         John:Doe:101
                Mary:Jane:202
                Bob:Coder:313

  Output:
                a[0]="John"
                a[1]="Mary"
                a[2]="Bob"
                b[0]="Doe"
                b[1]="Jane"
                b[2]="Coder"
                c[0]="101"
                c[1]="202"
                c[2]="313"

The query matches the data in three places, so each variable becomes
a list of three elements, reported as an array.

Variables with list bindings may be referenced in a query. They denote a
multiple match. The -D command line option can establish a one-dimensional
list binding.

Collect clauses may be nested.   Variable matches collated into lists in an
inner collect, are again collated into nested lists in the outer collect.
Thus an unbound variable wrapped in N nestings of @(collect) will
be an N-dimensional list. A one dimensional list is a list of strings;
a two dimensional list is a list of lists of strings, etc.

It is important to note that the variables which are bound within the main
clause of a collect---i.e. the variables which are subject to
collection---appear, within the collect, as normal one-value bindings. The
collation into lists happens outside of the collect. So for instance in the
query:

 @(collect)
 @x=@x
 @(end)

The left @x establishes a binding for some material preceding an equal sign.
The right @x refers to that binding. The value of @x is different in each
iteration, and these values are collected. What finally comes out of the
collect clause is list variable called x which holds each value that
was ever instantiated under that name within the collect clause.

Also note that the until clause has visibility over the bindings
established in the main clause. This is true even in the terminating
case when the until clause matches, and the bindings of the main clause
are discarded.

.SS Collect Keyword Parameters

By default, collect searches the rest of the input indefinitely,
or until the @(until) clause matches. It skips arbitrary amounts of
nonmatching material before the first match, and between matches.

Within the @(collect) syntax, it is possible to specify some useful keyword
parameters for additional control of the behavior. For instance

  @(collect :maxgap 5)

means that the collect will terminate if it does not find a match within five
lines of the starting position, or if more than five lines are skipped since
any successful match. A :maxgap of 0 means that the collected regions must be
adjacent. For instance:

  @(collect :maxgap 0)
  M @a
  @(end)

means: from here, collect consecutive lines of the form "M ...". This will not
search for the first such line, nor will it skip lines which do not match this
form.

Other keywords are :mingap, and :gap.  The :mingap keyword specifies a minimum
gap between matches, but has no effect on the distance to the first match. The
:gap keyword specifies  :mingap and :maxgap  at the same time, and can only be
used if these other two are not used. Thus:

 @(collect :gap 1)
 @a
 @(end)

means collect every other line starting with the current line. Several
other supported keywords are :times, :mintimes, :maxtimes and lines.
The shorthand :times N means the same thing as :mintimes N :maxtimes N.
These specify how many matches should be collected. If there are fewer
than mintimes matches, the collect fails. If maxtimes matches are collected,
collect stops collecting immediately. Example:

 @(collect :times 3)
 @a @b
 @(end)

This will collect a match for "@a @b" exactly three times. If three
matches are not found, it will fail.

The :lines parameter specifies the upper bound on how many lines
should be scanned by collect, measuring from the starting position.
The extent of the collect body is not counted. Example:

 @(collect :lines 2)
 foo: @a
 bar: @b
 baz: @c
 @(end)

The above collect will look for a match only twice: at the current position,
and one line down.

There is one more keyword, :vars, discussed in the following section.

.SS Specifying Variables in Collect

Normally, any variable for which a new binding occurs in a collect is
collected. A collect clause may be sloppy: it can neglect to collect some
variables on some iterations, or bind some variables which are intended
to behave like local temporaries, but end up collated into lists. Another issue
is that the collect clause might not match anything at all, and then none of
the variables are bound.

The :vars keyword allows the query writer to add discipline the collect body.

The argument to :vars is a list of variable specs. A variable spec is either a
symbol, or a (<symbol> <expression>) pair, where the expression specifies a
default value.

When a :vars list is specified, it means that only the given variables can
emerge from the successful collect. Any newly introduced bindings for other
variables do not propagate.

Furthermore, for any variable which is not specified with a default value, the
collect body, whenever it matches successfully, must bind that variable. If it
neglects to bind the variable, an exception of type query_error is thrown.
(If a collect body matches successfully, but produces no new bindings, then
this error is suppressed.)

For any variable which does have a default value, if the collect body neglects
to bind that variable, the behavior is as if the collect did bind that variable
to that default value.

The default values are expressions, and so can be quasiliterals.

Lastly, if in the event that the collect does not match anything, the variables
specified in vars (whether or not they have a default value) are all bound to
empty lists. (These bindings are established after the processing of the
until/last clause, if present.)

Example:

  @(collect :vars (a b (c "foo")))
  @a @c
  @(end)

Here, if the body "@a @c" matches, an error will be thrown because one of the
mandatory variables is b, and the body neglects to produce a binding for b.

Example:

  @(collect :vars (a (c "foo")))
  @a @b
  @(end)

Here, if "@a @b" matches, only a will be collected, but not b, because b is not
in the variable list. Furthermore, because there is no binding for c in the
body, a binding is created with the value "foo", exactly as if c matched
such a piece of text.

In the following example, the assumption is that THIS NEVER MATCHES
is not found anywhere in the input but the line THIS DOES MATCH is
found and has a successor which is bound to a. Because the body did not
match, the :vars a and b should be bound to empty lists. But a is bound
by the last clause to some text, so this takes precedence. Only b is bound to a
an empty list.

  @(collect :vars (a b))
  THIS NEVER MATCHES
  @(last)
  THIS DOES MATCH
  @a
  @(end)

The following means: do not allow any variables to propagate out of any
iteration of the collect and therefore collect nothing:

  @(collect :vars nil)
  ...
  @(end)

Instead of writing @(collect :vars nil), it is possible to write
@(repeat). @(repeat) takes all collect keywords, except for :vars.
There is a repeat directive used in @(output) clauses; that is
a different repeat directive.

.SS The Coll Directive

The coll directive is a kind of miniature version of the collect directive.
Whereas the collect directive works with multi-line clauses on line-oriented
material, coll works within a single line. With coll, it is possible to
recognize repeating regularities within a line and collect lists.

Regular-expression based Positive Match variables work well with coll.

Example: collect a comma-separated list, terminated by a space.

  pattern:  @(coll)@{A /[^, ]+/}@(until) @(end)@B
  data:     foo,bar,xyzzy blorch
  result:   A[0]="foo"
            A[1]="bar"
            A[2]="xyzzy"
            B=blorch

Here, the variable A is bound to tokens which match the regular
expression /[^, ]+/: non-empty sequence of characters other than commas or
spaces.

Like its big cousin, the coll directive searches for matches.  If no match
occurs at the current character position, it tries at the next character
position. Whenever a match occurs, it continues at the character position which
follows the last character of the match, if such a position exists.

If not bounded by an until clause, it will exhaust the entire line.  If the
until clause matches, then the collection stops at that position,
and any bindings from that iteration are discarded.
Like collect, coll also supports a last clause, which propagates varaible
bindings and advances the position.

Coll clauses nest, and variables bound within a coll are available to within
the rest of the coll clause, including the until clause, and appear as single
values.  The final list aggregation is only visible after the coll clause.

The behavior of coll is troublesome, when delimited variables are used,
because in text file formats, the material which separates items is not
repeated after the last item. For instance, a comma-separated list usually
not appear as "a,b,c," but rather "a,b,c". There might not be any explicit
termination---the last item might be at the very end of the line.

So for instance, the following result is not satisfactory:

  pattern:      @(coll)@a @(end)
  data:         1 2 3 4 5
  result:       a[0]="1"
                a[1]="2"
                a[2]="3"
                a[3]="4"

What happened to the 5? After matching "4 ", coll continues to look for
matches. It tries "5", which does not match, because it is not followed by a
space. Then the line is consumed.  So in this sequence, a valid item is either
followed by a space, or by nothing. So it is tempting to try this:

  pattern:      @(coll)@a@/ ?/@(end)
  data:         1 2 3 4 5
  result:       a[0]=""
                a[1]=""
                a[2]=""
                a[3]=""
                a[4]=""
                a[5]=""
                a[6]=""
                a[7]=""
                a[8]=""

however, the problem is that the regular expression / ?/ (match either a space
or nothing), matches at any position.  So when it is used as a variable
delimiter, it matches at the current position, which binds the empty string to
the variable, the extent of the match being zero. In this situation, the coll
directive proceeds character by character. The solution is to use
positive matching: specify the regular expression which matches the item,
rather than a trying to match whatever follows.  The collect directive will
recognize all items which match the regular expression.

  pattern:      @(coll)@{a /[^ ]+/}@(end)
  data:         1 2 3 4 5
  result:       a[0]="1"
                a[1]="2"
                a[2]="3"
                a[3]="4"
                a[4]="5"

The until clause can specify a pattern which, when recognized, terminates
the collection. So for instance, suppose that the list of items may
or may not be terminated by a semicolon. We must exclude
the semicolon from being a valid character inside an item, and
add an until clause which recognizes a semicolon:

  pattern:      @(coll)@{a /[^ ;]+/}@(until);@(end);

  data:         1 2 3 4 5;
  result:       a[0]="1"
                a[1]="2"
                a[2]="3"
                a[3]="4"
                a[4]="5"

  data:         1 2 3 4 5;
  result:       a[0]="1"
                a[1]="2"
                a[2]="3"
                a[3]="4"
                a[4]="5"

Semicolon or not, the items are collected properly.

Note that the @(end) is followed by a semicolon. That's because
when the @(until) clause meets a match, the matching material
is not consumed.

Instead of regular expression hacks, this problem can be nicely
solved with cases:

  pattern:      @(coll)@(cases)@a @(or)@a@(end)@(end)
  data:         1 2 3 4 5
  result:       a[0]="1"
                a[1]="2"
                a[2]="3"
                a[3]="4"
                a[4]="5"

.SS Coll Keyword Parameters

The @(coll) directive takes most of the same parameters as @(collect).
See the section Collect Keyword Parameters above.
So for instance @(coll :gap 0) means that the collects must be
consecutive, and @(coll :maxtimes 2) means that at most two matches
will be collected.  The :lines keyword does not exist, but there is
an analogous :chars keyword.

.SS The Flatten Directive.

The flatten directive can be used to convert variables to one dimensional
lists. Variables which have a scalar value are converted to lists containing
that value. Variables which are multidimensional lists are flattened to
one-dimensional lists.

Example (without @(flatten))

  pattern:      @b
                @(collect)
                @(collect)
                @a
                @(end)
                @(end)

  data:         0
                1
                2
                3
                4
                5

  result:       b="0"
                a_0[0]="1"
                a_1[0]="2"
                a_2[0]="3"
                a_3[0]="4"
                a_4[0]="5"

Example (with flatten):

  pattern:      @b
                @(collect)
                @(collect)
                @a
                @(end)
                @(end)
                @(flatten a b)

  data:         0
                1
                2
                3
                4
                5

  result:       b[0]="0"
                a[0]="1"
                a[1]="2"
                a[2]="3"
                a[3]="4"
                a[4]="5"

.SS The Merge Directive

The merge directive provides a way of combining two or more variables
in a somewhat complicated but very useful way. 

To understand what merge does we first have to define a property called depth.
The depth of an atom such as a string is defined as 1. The depth of an empty
list is 0. The depth of a nonempty list is one plus the depth of its deepest
element. So for instance "foo" has depth 1, ("foo") has depth 2, and ("foo"
("bar")) has depth three.

We can now define the binary (two argument) merge operation as follows.  (merge
A B) first normalizes the values A and B such that they have equal depth.
1. A value which has depth zero is put into a one element list. 
2. If either value has a smaller depth than the other, it is wrapped
in a list as many times as needed to give it equal depth.
Finally, the values are appended together.

Merge takes more than two arguments. These are merged by a left reduction. The
leftmost two values are merged, and then this result is merged with the third
value, and so on.

Merge is useful for combining the results from collects at different
levels of nesting such that elements are at the appropriate depth.

.SS The Cat Directive

The @(cat) directive converts a list variable into a single
piece of text. The syntax is:

 @(cat VAR [ SEP ])

The SEP argument specifies a separating piece of text. If no separator
is specified, then a single space is used.

Example:

  pattern:      @(coll)@{a /[^ ]+/}@(end)
                @(cat a ":")
  data:         1 2 3 4 5
  result:       a="1:2:3:4:5"


.SS The Bind Directive

The syntax of the @(bind) directive is:

  @(bind pattern expression { keyword value }*)

The @(bind) directive is a kind of pattern match, which matches one or more
variables on in the left hand side pattern to the value of a variable on the
right hand side.  The right hand side variable must have a binding, or else the
directive fails. Any variables on the left hand side which are unbound receive
a matching piece of the right hand side value. Any variables on the left which
are already bound must match their corresponding value, or the bind fails. Any
variables which are already bound and which do match their corresponding value
remain unchanged (the match can be inexact).

The simplest bind is of one variable against itself, for instance bind A
against A:

  @(bind A A)

This will fail if A is not bound, (and complain loudly). If A is bound, it
succeeds, since A matches A.

The next simplest bind binds one variable to another:

  @(bind A B)

Here, if A is unbound, it takes on the same value as B. If A is bound, it has
to match B, or the bind fails. Matching means that either
.IP -
A and B are the same text
.IP -
A is text, B is a list, and A occurs within B.
.IP -
vice versa: B is text, A is a list, and B occurs within A.
.IP -
A and B are lists and are either identical, or one is
found as substructure within the other.
.PP
The right hand side does not have to be a variable. It may be some other
object, like a string, quasiliteral, regexp, or list of strings, et cetera. For
instance

  @(bind A "ab\tc")

will bind the string "ab\tc" (the letter a, b, a tab character, and c)
to the variable A if A is unbound. If A is bound, this will fail unless
A already contains an identical string. However, the right hand side of
cannot be an unbound variable, nor a complex expression that contains unbound
variables.

The left hand side of a bind can be a nested list pattern containing variables.
The last item of a list at any nesting level can be preceded by a dot, which
means that the variable matches the rest of the list from that position.

Example: suppose that the list A contains ("now" "now" "brown" "cow"). Then the
directive @(bind (H N . C) A), assuming that H, N and C are unbound variables,
will bind H to "how", N to "now", and C to the remainder of the list ("brown"
"cow").

Example: suppose that the list A is nested to two dimensions and  contains
(("how" "now") ("brown" "cow")). Then @(bind ((H N) (B C)) A)
binds H to "how", N to "now", B to "brown" and C to "cow".

The dot notation may be used at any nesting level. it must be preceded and
followed by a symbol: the forms (.) (. X) and (X .) are invalid.

The number of items in a left pattern match must match the number of items in
the corresponding right side object. So the pattern () only matches
an empty list. The notation () and nil means exactly the same thing.

The symbols nil, t and keyword symbols may be used on either side.
They represent themselves.  For example @(bind :foo :bar) fails,
but @(bind :foo :foo) succeeds since the two sides denote the same
keyword symbol object.

.SS Keywords in The Bind Directive

The Bind directive accepts these keywords:

.IP :lfilt
The argument to :lfilt is a filter specification. When the left side pattern
contains a binding which is therefore matched against its counterpart from the
right side expression, the left side is filtered through the filter specified
by :lfilt for the purposes of the comparison. For example:

  @(bind "a" "A" :lfilt :upcase)

produces a match, since the left side is the same as the right after
filtering through the :upcase filter.

.IP :rfilt
The argument to :rfilt is a filter specification. The specified filter is
applied to the right hand side material prior to matching it against
the left side. The filter is not applied if the left side is a variable
with no binding. It is only applied to determine a match. Binding takes
place the unmodified right hand side object.

Example, the following produces a match:

  @(bind "A" "a" :rfilt :upcase)

.IP :filter
This keyword is a shorthand to specify both filters to the same value.
So for instance :filter :upcase is equivalent to :lfilt :upcase :rfilt :upcase.

For a description of filters, see Output Filtering below.

Of course, compound filters like (:from_html :upcase) are supported with
all these keywords. The filters apply across arbitrary patterns and nested data.

Example:

  @(bind (a b c) ("A" "B" "C"))
  @(bind (a b c) (("z" "a") "b" "c") :rfilt :upcase)

Here, the first bind establishes the values for a, b and c, and the second bind
succeeds, because the value of a matches the second element of the list ("z"
"a") if it is upcased, and likewise b matches "b" and c matches "c" if these
are upcased.

.SS The Set Directive

The @(set) directive resembles bind, but is not a pattern match. It overwrites
the previous values of variables with new values from the right hand side.
Each variable that is assigned must have an existing binding.

Examples follow.

Store the value of A back into A, achieving nothing:

  @(set A A)

Exchange the values of A and B:

  @(set (A B) (B A))

Store a string into A:

  @(set A "text")

Store a list into A:

  @(set A ("line1" "line2"))

Destructuring assignment. D assumed to contain the list 

  @(bind D ("A" ("B1" "B2") "C1" "C2"))
  @(bind (A B C) (() () ()))
  @(set (A B . C) D)

A ends up with "A", B ends up with ("B1" "B2") and C gets ("C1" and "C2").

.SS The Rebind Directive

The @(rebind) directive resembles @(set) but it is not an assignment.
It combines the semanticss of @(local), @(bind) and @(set).
The expression on the right hand side is evaluated in the current
environment. Then the variables in the pattern on the left are introduced
as new bindings, whose values come from the pattern.

Rebind makes it easy to create temporary bindings based on existing
bindings.

  @(define pattern-function (arg))
  @;; inside a pattern function:
  @(rebind recursion-level @(+ recursion-level 1))
  @;; ...
  @(end)

When the function terminates, the previous value of recursion-level
is restored. The effect is like the following, but much easier
to write and faster to execute:

  @(define pattern-function (arg))
  @;; inside a pattern function:
  @(local temp)
  @(set temp recursion-level)
  @(local recursion-level)
  @(set recursion-level @(+ temp 1))
  @;; ...
  @(end)

.SH BLOCKS

.SS Introduction

Blocks are sections of a query which are denoted by a name. Blocks denoted by
the name nil are understood as anonymous.

The @(block NAME) directive introduces a named block, except when the name is
the word nil.  The @(block) directive introduces an unnamed block, equivalent
to @(block nil).

The @(skip) and @(collect) directives introduce implicit anonymous blocks,
as do function bodies.

Blocks are useful for terminating parts of a pattern matchin search
prematurely, and escaping to a higher level. This makes blocks not only
useful for simplifying the semantics of certain pattern matches,
but also an optimization tool. 

Judicious use of blocks and escapes can reduce or eliminate the amount
backtracking that TXR performs.

.SS Block Scope

The names of blocks are in a distinct namespace from the variable binding
space. So @(block foo) has no interaction with the variable @foo.

A block extends from the @(block ...) directive which introduces it,
until the matching @(end), and may be empty.  For instance:

  @(some)
  abc
  @(block foo)
  xyz
  @(end)
  @(end)

Here, the block foo occurs in a @(some) clause, and so it extends to the @(end)
which terminates the block.  After that @(end), the name foo is not
associated with a block (is not "in scope"). The second @(end) terminates
the @(some) block. 

The implicit anonymous block introduced by @(skip) has the same scope
as the @(skip): it extends over all of the material which follows the skip,
to the end of the containing subquery.

.SS Block Nesting

Blocks may nest, and nested blocks may have the same names as blocks in
which they are nested. For instance:

  @(block)
  @(block)
  ...
  @(end)
  @(end)

is a nesting of two anonymous blocks, and

  @(block foo)
  @(block foo)
  @(end)
  @(end)

is a nesting of two named blocks which happen to have the same name.
When a nested block has the same name as an outer block, it creates
a block scope in which the outer block is "shadowed"; that is to say,
directives which refer to that block name within the nested block refer to the
inner block, and not to the outer one.

.SS Block Semantics

A block normally does nothing. The query material in the block is evaluated
normally. However, a block serves as a termination point for @(fail) and
@(accept) directives which are in scope of that block and refer to it.

The precise meaning of these directives is:

.IP "@(fail NAME)"

Immediately terminate the enclosing query block called NAME, as if that block failed to match anything. If more than one block by that name encloses
the directive, the inner-most block is terminated. No bindings
emerge from a failed block.

.IP @(fail)

Immediately terminate the innermost enclosing anonymous block, as if
that block failed to match.

If the implicit block introduced by @(skip) is terminated in this manner,
this has the effect of causing the skip itself to fail. I.e. the behavior
is as if skip search did not find a match for the trailing material,
except that it takes place prematurely (before the end of the available
data source is reached).

If the implicit block associated with a @(collect)  is terminated this way,
then the entire collect fails. This is a special behavior, because a
collect normally does not fail, even if it matches and collects nothing!

To prematurely terminate a collect by means of its anonymous block, without
failing it, use @(accept).

.IP "@(accept NAME)"

Immediately terminate the enclosing query block called NAME, as if that block
successfully matched. If more than one block by that name encloses the
directive, the inner-most block is terminated.  Any bindings established within
that block until this point emerge from that block.

.IP @(accept)

Immediately terminate the innermost enclosing anonymous block, as if
that block successfully matched. Any bindings established within
that block until this point emerge from that block.

If the implicit block introduced by @(skip) is terminated in this manner,
this has the effect of causing the skip itself to succeed, as if
all of the trailing material successfully matched.

If the implicit block associated with a @(collect)  is terminated this way,
then the collection stops. All bindings collected in the current iteration of
the collect are discarded. Bindings collected in previous iterations are
retained, and collated into lists in accordance with the semantics of collect.

Example: alternative way to @(until) termination:

  @(collect)
  @  (maybe)
  ---
  @  (accept)
  @  (end)
  @LINE
  @(end)

This query will collect entire lines into a list called LINE. However,
if the line --- is matched (by the embedded @(maybe)), the collection
is terminated. Only the lines up to, and not including the --- line,
are collected. The effect is identical to:

  @(collect)
  @LINE
  @(until)
  ---
  @(end)

The difference (not relevant in these examples) is that the until clause has
visibility into the bindings set up by the main clause.

However, the following example has a different meaning:

  @(collect)
  @LINE
  @  (maybe)
  ---
  @  (accept)
  @  (end)
  @(end)

Now, lines are collected until the end of the data source, or until a line is
found which is followed by a --- line. If such a line is found,
the collection stops, and that line is not included in the collection!
The @(accept) terminates the process of the collect body, and so the
action of collecting the last @LINE binding into the list is not performed.

.SS Data Extent of Terminated Blocks

A query block may have matched some material prior to being terminated by
accept. In that case, it is deemed to have only matched that material,
and not any material which follows. This may matter, depending on the context
in which the block occurs.

Example:

  Query:        @(some)
                @(block foo)
                @first
                @(accept foo)
                @ignored
                @(end)
                @second

  Data:         1
                2
                3

  Output:       first="1"
                second="2"

At the point where the accept occurs, the foo block has matched the first line,
bound the text "1" to the variable @first. The block is then terminated.
Not only does the @first binding emerge from this terminated block, but
what also emerges is that the block advanced the data past the first line to
the second line. So next, the @(some) directive ends, and propagates the
bindings and position. Thus the @second which follows then matches the second
line and takes the text "2".

In the following query, the foo block occurs inside a maybe clause.
Inside the foo block there is a @(some) clause. Its first subclause
matches variable @first and then terminates block foo. Since block foo is
outside of the @(some) directive, this has the effect of terminating the
@(some) clause:

  Query:        @(maybe)
                @(block foo)
                @  (some)
                @first
                @  (accept foo)
                @  (or)
                @one
                @two
                @three
                @four
                @  (end)
                @(end)
                @second

  Data:         1
                2
                3
                4
                5

  Output:       first="1"
                second="2"

The second clause of the @(some) directive, namely:

  @one
  @two
  @three
  @four

is never processed. The reason is that subclauses are processed in top
to bottom order, but the processing was aborted within the
first clause the @(accept foo). The @(some) construct never had the
opportunity to match four lines.

If the @(accept foo) line is removed from the above query, the output
is different:

  Query:        @(maybe)
                @(block foo)
                @  (some)
                @first
                @#          <--  @(accept foo) removed from here!!!
                @  (or)
                @one
                @two
                @three
                @four
                @  (end)
                @(end)
                @second

  Data:         1
                2
                3
                4
                5

  Output:       first="1"
                one="1"
                two="2"
                three="3"
                four="4"
                second="5"

Now, all clauses of the @(some) directive have the opportunity to match.
The second clause grabs four lines, which is the longest match.
And so, the next line of input available for matching is 5, which goes
to the @second variable.

.SS Interaction between Trailer and Accept Directives

If one of the clauses which follow a @(trailer) request a successful
termination to an outer block via @(accept), then @(trailer) intercepts
the transfer and adjusts the data extent to the position that it was given.

Example:

  Query:        @(block)
                @(trailer)
                @line1
                @line2
                @(accept)
                @(end)
                @line3

  Data:         1
                2
                3

  Output:       line1="1"
                line2="2"
                line3="1"

The variable line3 is bound to 1 because although the @(accept) yields a data
position which is advanced to the third line, this is intercepted by @(trailer)
and adjusted back to the first line.

Directives other than @(trailer) have no such special interaction with accept.

.SH FUNCTIONS

.SS Introduction

.B TXR
functions allow a query to be structured to avoid repetition.
On a theoretical note, because
.B TXR
functions support recursion, functions enable TXR to match some
kinds of patterns which exhibit self-embedding, or nesting,
and thus cannot be matched by a regular language.

Functions in
.B TXR
are not exactly like functions in mathematics or functional languages, and are
not like procedures in imperative programming languages. They are not exactly
like macros either. What it means for a
.B TXR
function to take arguments and produce a result is different from
the conventional notion of a function.

A
.B TXR
function may have one or more parameters. When such a function is invoked, an
argument must be specified for each parameter.  However, a special behavior is
at play here. Namely, some or all of the argument expressions may be unbound
variables.  In that case, the corresponding parameters behave like unbound
variables also.  Thus
.B TXR
function calls can transmit the "unbound" state from argument to parameter.

It should be mentioned that functions have access to all bindings that are
visible in the caller; functions may refer to variables which are not
mentioned in their parameter list.

With regard to returning,
.B TXR
functions are also unconventional. If the function fails, then the function
call is considered to have failed. The function call behaves like a kind of
match; if the function fails, then the call is like a failed match.

When a function call succeeds, then the bindings emanating from that function
are processed specially. Firstly, any bindings for variables which do not
correspond to one of the function's parameters are thrown away. Functions may
internally bind arbitrary variables in order to get their job done, but only
those variables which are named in the function argument list may propagate out
of the function call.  Thus, a function with no arguments can only indicate
matching success or failure, but not produce any bindings. Secondly,
variables do not propagate out of the function directly, but undergo
a renaming. For each parameter which went into the function as an unbound
variable (because its corresponding argument was an unbound variable),
if that parameter now has a value, that value is bound onto the corresponding
argument.

Example:

  @(define collect_words (list))
  @(coll)@{list /[^ \t]/}@(end)
  @(end)

The above function "collect_words" contains a query which collects words from a
line (sequences of characters other than space or tab), into the list variable
called "list".  This variable is named in the parameter list of the function,
therefore, its value, if it has one, is permitted to escape from the function
call.

Suppose the input data is:

  Fine summer day

and the function is called like this:

  @(collect_words wordlist)

The result is:

  wordlist[0]=Fine
  wordlist[1]=summer
  wordlist[1]=day

How it works is that in the function call @(collect_words wordlist),
"wordlist" is an unbound variable. The parameter corresponding to that
unbound variable is the parameter "list". Therefore, that parameter
is unbound over the body of the function.  The function body collects the
words of "Fine summer day" into the variable "list", and then
yields the that binding.   Then the function call completes by
noticing that the function parameter "list" now has a binding, and
that the corresponding argument "wordlist" has no binding. The binding
is thus transferred to the "wordlist" variable.  After that, the
bindings produced by the function are thrown away. The only enduring
effects are:
.IP -
the function matched and consumed some input; and
.IP -
the function succeeded; and
.IP -
the wordlist variable now has a binding.
.PP
Another way to understand the parameter behavior is that function
parameters behave like proxies which represent their arguments.  If an argument
is an established value, such as a character string or bound variable, the
parameter is a proxy for that value and behaves just like that value. If an
argument is an unbound variable, the function parameter acts as a proxy
representing that unbound variable. The effect of binding the proxy is
that the variable becomes bound, an effect which is settled when the
function goes out of scope.

Within the function, both the original variable and the proxy are
visible simultaneously, and are independent.  What if a function binds both of
them? Suppose a function has a parameter called P, which is called
with an argument A, and then in the function @A and @P are bound.  This is
permitted, and they can even be bound to different values.  However, when the
function terminates, the local binding of A simply disappears (because,
remember, the symbol A is not a member of the list of parameters).
Only the value bound to P emerges, and is bound to A, which still appears
unbound at that point.

.SS Definition Syntax

Function definition syntax comes in two flavors: vertical and horizontal.
Horizontal definitions actually come in two forms, the distinction
between which is hardly noticeable, and the need for which is
made clear below.

A function definition begins with a @(define ...) directive. For vertical
functions, this is the only element in a line.

The define symbol must be followed by a symbol, which is the name of the
function being defined. After the symbol, there is a parenthesized optional
argument list. If there is no such list, or if the list is specified as () or
the symbol "nil" then the function has no parameters. Examples of valid define
syntax are:

  @(define foo)
  @(define bar ())
  @(define match (a b c))

If the define directive is followed by more material on the same line, then it
it defines a horizontal function:

  @(define match_x)x@(end)

If the define is the sole element in a line, then it
is a vertical function, and the function definition continues below:

  @(define match_x)
  x
  @(end)

The difference between the two is that a horizontal function matches
characters within a line, whereas a vertical function matches lines
within a stream. The former match_x matches the character x, advancing
to the next character position.  The latter match_x matches a line consisting
of the character x, advancing to the next line.

Material between @(define) and @(end) is the function body.  The define
directive may be followed directly by the @(end) directive, in which case the
function has an empty body.

Functions may be nested within function bodies. Such local functions have
dynamic scope. They are visible in the function body in which they are defined,
and in any functions invoked from that body.

The body of a function is an anonymous block. (See BLOCKS above).

.SS Two Forms of The Horizontal Function

If a horizontal function is defined as the only element of a line,
it may not be followed by additional material. The following
construct is erroneous:

  @(define horiz (x))@foo:@bar@(end)lalala

This kind of definition is actually considered to be in the vertical context,
and like other directives that have special effects and that do not match
anything, it does not consume a line of input. If the above syntax were
allowed, it would mean that the line would not only define a function but also
match "lalala".  This would, in turn, would mean that the @(define)...@(end) is
actually in horizontal mode, and so it matches a span of zero characters within
a line (which means that is would require a line of input to match: a nasty
thing for a non-matching directive to do!) 

A horizontal function can be defined in an actual horizontal context. This
occurs if its is in a line where it is preceded by other material.
For instance:

  X@(define fun)...@(end)Y

This is a query line which must match the text XY. It also defines the function
fun. The main use of this form is for nested horizontal functions:

  @(define fun)@(define local_fun)...@(end)@(end)

.SS Vertical-Horizontal Overloading

A function of the same name may be defined as both vertical and horizontal.
Both functions are available at the same time. Which one is used by
a call is resolved by context. See the section Vertical Versus Horizontal Calls below.

.SS Call Syntax

A function is invoked by compound directive whose first symbol is the name of
that function. Additional elements in the directive are the arguments.
Arguments may be symbols, or other objects like string and character
literals, quasiliterals ore regular expressions.

Example:

  Query:         @(define pair (a b))
                 @a @b
                 @(end)
                 @(pair first second)
                 @(pair "ice" cream)
 
  Data:          one two
                 ice milk
 
  Output:        first="one"
                 second="two"
                 cream="milk"

The first call to the function takes the line "one two". The parameter "a"
takes "one" and parameter b takes "two". These are rebound to the arguments
first and second. The second call to the function binds the a parameter
to the word "ice", and the b is unbound, because the
corresponding argument "cream" is unbound. Thus inside the function, @a
is forced to match "ice". Then a space is matched and @b collects the text
"milk". When the function returns, the unbound "cream" variable gets this value.

If a symbol occurs multiple times in the argument list, it constrains
both parameters to bind to the same value. That is to say, all parameters
which, in the body of the function, bind a value, and which are all derived
from the same argument symbol must bind to the same value. This is settled when
the function terminates, not while it is matching. Example:

  Query:         @(define pair (a b))
                 @a @b
                 @(end)
                 @(pair same same)
 
  Data:          one two

  Output:        [query fails, prints "false"]


.SS Vertical Versus Horizontal Calls

A function call which is the only element of the query line in
which it occurs is ambiguous. It can go either to a vertical
function or to the horizontal one. If both are defined, then
it goes to the vertical one.

Example:

  Query:          @(define which (x))@(bind x "horizontal")@(end)
                  @(define which (x))
                  @(bind x "vertical")
                  @(end)
                  @(which fun)

  Output:         fun="vertical"

Not only does this call go to the vertical function, but
it is in a vertical context.

If only a horizontal function is defined, then that is the one which is called,
even if the call is the only element in the line. This takes place in a
horizontal character-matching context, which requires a line of input which can
be traversed:

Example:

  Query:          @(define which (x))@(bind x "horizontal")@(end)
                  @(which fun)

  Data:           ABC

  Output:         false

The query failed. Why? Because since @(which fun) is in horizontal mode,
it matches characters in a line. Since the function body consists
of @(bind ...) which doesn't match any characters, the function
call requires an empty line to match. The line ABC is not empty,
and so there is a matching failure. The following
example corrects this:

Example:

  Query:          @(define which (x))@(bind x "horizontal")@(end)
                  @(which fun)

  Data:           <empty line>

  Output:         fun="horizontal"

A call made in a clearly horizontal context will prefer the
horizontal function, and only fall back on the vertical one
if the horizontal one doesn't exist. (In this fall-back case,
the vertical function is called with empty data; it is useful
for calling vertical functions which process arguments and
produce values.)

In the next example, the call is followed by trailing material,
placing it in a horizontal context. Leading material will
do the same thing:

Example:

  Query:          @(define which (x))@(bind x "horizontal")@(end)
                  @(define which (x))
                  @(bind x "vertical")
                  @(end)
                  @(which fun)B

  Data:           B

  Output:         fun="horizontal"

.SS Nested Functions

Function definitions may appear in a function. Such definitions
are visible in all functions which are invoked from the body
(and not necessarily enclosed in the body). In other words, the
scope is dynamic, not lexical.  Inner definitions shadow outer
definitions. This means that a caller can redirect the function
calls that take place in a callee, by defining local functions
which capture the references.

Example:

  Query:        @(define which)
                @  (fun)
                @(end)
                @(define fun)
                @  (output)
                toplevel fun!
                @  (end)
                @(end)
                @(define callee)
                @  (define fun)
                @    (output)
                local fun!
                @    (end)
                @  (end)
                @  (which)
                @(end)
                @(callee)
                @(which)

   Output:      local fun!
                toplevel fun!

Here, the function "which" is defined which calls "fun".
A toplevel definition of "fun" is introduced which
outputs "toplevel fun!".  The function "callee" provides its own local
definition of "fun" which outputs "local fun!" before calling "which".  When
callee is invoked, it calls @(which), whose @(fun) call is routed to callee's
local definition.  When @(which) is called directly from the top level, its
@(fun) call goes to the toplevel definition.

.SH MODULARIZATION

.SS The Load Directive

The syntx of the load directive is:

  @(load EXPR)

Where EXPR evaluates to a string giving the path of the file to load.
Unless the path is absolute, it is interpreted relative to the directory of the
source file from which the @(load) form was read. If there was no such
source file (for instance, the script was read from standard input),
then it is resolved relative to the current working directory.

If the file cannot be opened, then the .txr suffix is added and another
attempt is made. Thus load expressions need not refer to the suffix.
In the future, additional suffixes may be searched (compiled versions
of a file).

Loading is performed at evaluation time; it is not a source file inclusion
mechanism.  A TXR script is read from beginning to end and parsed prior to
being evaluated.

See also: the *self-path* variable in TXR Lisp.

.SH OUTPUT

.SS Introduction

A
.B TXR
query may perform custom output. Output is performed by @(output) clauses,
which may be embedded anywhere in the query, or placed at the end.  Output
occurs as a side effect of producing a part of a query which contains an
@(output) directive, and is executed even if that part of the query ultimately
fails to find a match. Thus output can be useful for debugging.
An output clause specifies that its output goes to a file, pipe, or (by
default) standard output. If any output clause is executed whose destination is
standard output,
.B TXR
makes a note of this, and later, just prior to termination, suppresses the
usual printing of the variable bindings or the word false.

.SS The Output Directive

The syntax of the @(output) directive is:

  @(output [ DESTINATION ] { bool-keyword | keyword value }* )
  .
  . one or more output directives or lines
  .
  @(end)

The optional destination is a filename, the special name, - which
redirects to standard output, or a shell command preceded by the ! symbol.
In the first form, the destination may be specified as a variable
which holds text, a string literal or a quasiliteral

The keyword list consists of a mixture of boolean keywords which
do not have an argument, or keywords with arguments.

The following boolean keywords are supported:

.IP :nothrow

The output directive throws an exception if the output destination
cannot be opened, unless the :nothrow keyword is present, in which
case the situation is treated as a match failure.  

Note that since command pipes are processes that report errors
asynchronously, a failing command will not throw an immediate exception that
can be suppressed with :nothrow.   This is for synchronous errors, like
trying to open a destination file, but not having permissions, etc.

.IP :append

This keyword is meaningful for files, specifying append mode: the output is to
be added to the end of the file rather than overwriting the file.

The following value keywords are supported:

.IP :filter

The argument can be a symbol, which specifies a filter to be applied to
the variable substitutions occuring within the output clause.
The argument can also be a list of filter symbols, which specifies
that multiple filters are to be applied, in left to right order.

See the later sections Output Filtering below, and The Deffilter Directive.

.IP :into

The argument of :into is a symbol which denotes a variable.
The output will go into that variable.  If the variable is unbound,
it will be created. Otherwise, its contents are overwritten
unless the :append keyword is used. If :append is used, then
the new content will be appened to the previous content of
the variable, after flattening the content to a list,
as if by the @(flatten) directive.

.SS Output Text

Text in an output clause is not matched against anything, but is output
verbatim to the destination file, device or command pipe.

.SS Output Variables

Variables occurring in an output clause do not match anything, but instead
their contents are output.

A variable being output can be any object. If it is of a type other
than a string, it will be converted to a string as if by the tostring
function in TXR Lisp.

A list is converted to a string in a special way: the elements are
individually converted to a string and then they are catenated together.
The default separator string is a single space: an alternate separation
can be specified as an argument in the brace substitution syntax.

Lists may be output within @(repeat) or @(rep) clauses. Each nesting of
these constructs removes one level of nesting from the list variables
that it contains.

In an output clause, the @{NAME NUMBER} variable syntax generates fixed-width
field, which contains the variable's text.  The absolute value of the
number specifies the field width. For instance -20 and 20 both specify a field
width of twenty.  If the text is longer than the field, then it overflows the
field. If the text is shorter than the field, then it is left-adjusted within
that field, if the width is specified as a positive number, and right-adjusted
if the width is specified as negative.

An output variable may specify a filter which overrides any filter established
for the output clause. The syntax for this is @(NAME :filter <filterspec>}.
The filter specification syntax is the same as in the output clause.
See Output Filtering below.

.SS Output Variables: Indexing

Additional syntax is supported in output variables that is does not appear
in pattern matching variables.

A square bracket index notation may be used to extract elements or
ranges from a variable, which works with strings, vectors and lists.  Elements
are indexed from zero. This notation is only available in brace-enclosed
syntax, and looks like this:

.IP
@{NAME[expr]} 

Extract the element at the position given by expr.

.IP
@{NAME[expr1..expr2]}

Extract a range of elements from the position given by expr1, up to
one position less than the position given by expr2.

If the variable is a list, it is treated as a list substitution,
exactly as if it were the value of an unsubscripted list variable.
The elements of the list are converted to strings and catenated
together wit ha separator string between them, the default one being
a single space.

An alternate character may be given as a string argument in the brace
notation.

.TP
Example:

  @(bind a ("a" "b" "c" "d"))
  @(output)
  @{a[1..3] "," 10}
  @(end)

The above produces the text "b,c" in a field 10 spaces wide. The [1..3]
argument extracts a range of a; the "," argument specifies an alternate
separator string, and 10 specifies the field width.

.SS Output Substitutions

The brace syntax has another syntactic and semantic extension. In place
of the symbol, an expression may appear. The value of that expression
is substituted.

Example:

 @(bind a "foo")
 @(output)
 @{`@a:` -10}

Here, the quasiliteral expression `@a:` is evaluated, producing the string
"foo:". This string is printed right-adjusted in a 10 character field.

.SS The Repeat Directive

The repeat directive is generates repeated text from a ``boilerplate'',
by taking successive elements from lists. The syntax of repeat is
like this:

  @(repeat)
  .
  .
  main clause material, required
  .
  .
  special clauses, optional
  .
  .
  @(end)

Repeat has four types of special clauses, any of which may be
specified with empty contents, or omitted entirely. They are described
below.

Repeat takes arguments, also described below.

All of the material in the main clause and optional clauses
is examined for the presence of variables.  If none of the variables
hold lists which contain at least one item, then no output is performed,
(unless the repeat specifies an @(empty) clause, see below).
Otherwise, among those variables which contain non-empty lists, repeat finds
the length of the longest list. This length of this list determines the number
of repetitions, R.

If the repeat contains only a main clause, then the lines of this clause is
output R times. Over the first repetition, all of the variables which, outside
of the repeat, contain lists are locally rebound to just their first item. Over
the second repetition, all of the list variables are bound to their second
item, and so forth. Any variables which hold shorter lists than the longest
list eventually end up with empty values over some repetitions.

Example: if the list A holds "1", "2" and "3"; the list B holds "A", "B";
and the variable C holds "X", then

  @(repeat)
  >> @C
  >> @A @B
  @(end)

will produce three repetitions (since there are two lists, the longest
of which has three items). The output is:

  >> X
  >> 1 A
  >> X
  >> 2 B
  >> X
  >> 3

The last line has a trailing space, since it is produced by "@A @B",
where @B has an empty value. Since C is not a list variable, it
produces the same value in each repetition.

The special clauses are:

.IP @(single)
If the repeat produces exactly one repetition, then the contents of this clause
are processed for that one and only repetition, instead of the main clause
or any other clause which would otherwise be processed.

.IP @(first)
The body of this clause specifies an alternative body to be used for the first
repetition, instead of the material from the main clause.

.IP @(last)
The body of this clause is used instead of the main clause for the last
repetition.

.IP @(empty)
If the repeat produces no repetitions, then the body of this clause is output.
If this clause is absent or empty, the repeat produces no output.

.IP "@(mod n m)"
The forms n and m are expressions that evaluate to integers. The value of
m should be nonzero. The clause denoted this way is active if the repetition
modulo m is equal to n. The first repetition is numbered zero.
For instance the clause headed by @(mod 0 2) will be used on repetitions 
0, 2, 4, 6, ...  and @(mod 1 2) will be used on repetitions 1, 3, 5, 7, ...

.IP "@(modlast n m)"
The meaning of n and m is the same as in @(mod n m), but one more condition
is imposed. This clause is used if the repetition modulo m is
equal to n, and if it is the last repetition.

.PP
The precedence among the clauses which take an iteration is:
single > first > mod > modlast > last > main.  That is if two or more of these
clauses can apply to a repetition, then the leftmost one in this precedence
list applies. For instance, if there is just a single repetition, then any of
these special clause types can apply to that repetition, since it is the only
repetition, as well as the first and last one. In this situation, if there is a
@(single) clause present, then the repetition is processed using that clause.
Otherwise, if there is a @(first) clause present, that clause is used. Failing
that, @(mod) is used if there is such a clause and its numeric conditions
are satisfied. If not then @(modlast) clauses are considered, and if there
are none, or none of them activate, then @(last) is considered. If none
of those clauses are present or apply, then the repetition is processed
using the main clause.

Repeat supports an optional keyword argument:

  @(repeat [:counter <symbol>])

This designates a symbol which will behave as an integer variable over the
scope of the clauses inside the repeat. The variable provides access to the
reptition count, starting at zero, incrementing with each repetition.

.SS Nested Repeats

If a repeat clause encloses variables which holds multidimensional lists,
those lists require additional nesting levels of repeat (or rep).
It is an error to attempt to output a list variable which has not been
decimated into primary elements via a repeat construct.

Suppose that a variable X is two-dimensional (contains a list of lists).  X
must be twice nested in a repeat. The outer repeat will walk over the lists
contained in X. The inner repeat will walk over the elements of each of these
lists.

A nested repeat may be embedded in any of the clauses of a repeat,
not only the main clause.

.SS The Rep Directive

The @(rep) directive is similar to @(repeat), but whereas @(repeat) is line
oriented, @(rep) generates material within a line. It has all the same clauses,
but everything is specified within one line:

  @(rep)... main material ... .... special clauses ...@(end)

More than one @(rep) can occur within a line, mixed with other material.
A @(rep) can be nested within a @(repeat) or within another @(rep).

.SS Repeat and Rep Examples

Example 1: show the list L in parentheses, with spaces between
the elements, or the symbol NIL if the list is empty:

  @(output)
  @(rep)@L @(single)(@L)@(first)(@L @(last)@L)@(empty)NIL@(end)
  @(end)

Here, the @(empty) clause specifies NIL. So if there are no repetitions,
the text NIL is produced. If there is a single item in the list L,
then  @(single)(@L) produces that item between parentheses.  Otherwise
if there are two or more items, the first item is produced with
a leading parenthesis followed by a space by @(first)(@L , and
the last item is produced with a closing parenthesis: @(last)@L).
All items in between are emitted with a trailing space by
the main clause: @(rep)@L .

Example 2: show the list L like Example 1 above, but the empty list is ().

  @(output)
  (@(rep)@L @(last)@L@(end))
  @(end)

This is simpler. The parentheses are part of the text which
surrounds the @(rep) construct, produced unconditionally.
If the list L is empty, then @(rep) produces no output, resulting in ().
If the list L has one or more items, then they are produced with
spaces each one, except the last which has no space.
If the list has exactly one item, then the @(last) applies to it
instead of the main clause: it is produced with no trailing space.

.SS Output Filtering

Often it is necessary to transform the output to preserve its meaning
under the convention of a given data format. For instance, if a piece of
text contains the characters < or >, then if that text is being
substituted into HTML, these should be replaced by &lt; and &gt;.
This is what filtering is for.  Filtering is applied to the contents of output
variables, not to any template text.
.B TXR
implements named filters.  Built-in filters are named by keywords,
given below. User-defined filters are possible, however.  See notes on the
deffilter directive below.

Instead of a filter name, the syntax (fun NAME) can be used. This
denotes that the function called NAME is to be used as a filter.
This is discussed in the next section Function Filters below.

Built-in filters named by keywords:

.IP :to_html
Filter text to HTML, representing special characters using HTML
ampersand sequences. For instance '>' is replaced by '&gt;'.

.IP :from_html
Filter text with HTML codes into text in which the codes are replaced by the
corresponding characters. For instance '&gt;' is replaced by '>'.

.IP :upcase
Convert the 26 lower case letters of the English alphabet to upper case.

.IP :downcase
Convert the 26 upper case letters of the English alphabet to lower case.

.IP :frompercent
Decode percent-encoded text. Character triplets consisting
of the % character followed by a pair of hexadecimal digits (case insensitive)
are are converted to bytes having the value represented by the hexadecimal
digits (most significant nybble first). Sequences of one or more such bytes are
treated as UTF-8 data  and decoded to characters.

.IP :topercent
Convert to percent encoding according to RFC 3986. The text is first converted
to UTF-8 bytes. The bytes are then converted back to text as follows.
Bytes in the range 0 to 32, and 127 to 255 (note: including the ASCII DEL), 
bytes whose values correspond to ASCII characters which are listed by RFC 3986 
as being in the "reserved set", and the byte value corresponding to the
ASCII % character are encoded as a three-character sequence consisting
of the % character followed by two hexadecimal digits derived from the
byte value (most significant nybble first, upper case). All other bytes
are converted directly to characters of the same value without any such
encoding.

.IP :fromurl
Decode from URL encoding, which is like percent encoding, except that
if the unencoded + character occurs, it is decoded to a space character.
Of course %20 still decodes to space, and %2B to the + character.

.IP :tourl
Encode to URL encoding, which is like percent encoding except that
a space maps to + rather than %20. The + character, being in the
reserved set, encodes to %2B.

.PP :tonumber
Converts strings to numbers. Strings that contain a period, e or E are
converted to floating point as if by the function flo-str. Otherwise
they are converted to integer as if using int-str with a radix of 10.
Non-numeric junk results in the object nil.

.PP :tointeger
Converts strings to integers as if using int-str with a radix of 10.
Non-numeric junk results in the object nil.

.PP :tofloat
Converts strings to floating-point values as if using the function flo-str.
Non-numeric junk results in the object nil.

.PP :hextoint
Converts strings to integers as if using int-str with a radix of 16.
Non-numeric junk results in the object nil.

.PP

.TP
Examples

To escape HTML characters in all variable substitutions occuring in an
output clause, specify :filter :to_html in the directive:

  @(output :filter :to_html)
  ...
  @(end)

To filter an individual variable, add the syntax to the variable spec:

  @(output)
  @{x :filter :to_html}
  @(end)

Multiple filters can be applied at the same time. For instance:

  @(output)
  @{x :filter (:upcase :to_html)}
  @(end)

This will fold the contents of x to upper case, and then encode any special
characters into HTML. Beware of combinations that do not make sense.
For instance, suppose the original text is HTML, containing codes
like '&quot;'. The compound filter (:upcase :from_html) will not work
because '&quot;' will turn to '&QUOT;' which no longer be recognized
by the :from_html filter, because the entity names in HTML codes
are case-sensitive.

Capture some numeric variables and convert to numbers:

  @date @time @temperature @pressure
  @(filter :tofloat temperature pressure)
  @;; temperature and pressure can now be used in calculations

.SS Function Filters

A function can be used as a filter. For this to be possible, the function must
conform to certain rules:

.IP 1.
The function must take two special arguments, which may be followed
by additional arguments.

.IP 2.
When the function is called, the first argument will be bound to a string,
and the second argument will be unbound. The function must produce a 
value by binding it to the second argument. If the filter is to be used
as the final filter in a chain, it must produce a string.

For instance, the following is a valid filter function:

  @(define foo_to_bar (in out))
  @  (next :string in)
  @  (cases)
  foo
  @    (bind out "bar")
  @  (or)
  @    (bind out in)
  @  (end)
  @(end)

This function binds the out parameter to "bar" if the in parameter
is "foo", otherwise it binds the out parameter to a copy of the in parameter.
This is a simple filter.

To use the filter, use the syntax (:fun foo_to_bar) in place of a filter name. 
For instance in the bind directive:

  @(bind "foo" "bar" :lfilt (:fun foo_to_bar))

The above should succeed since the left side is filtered from "foo"
to "bar", so that there is a match.

Of course, function filters can be used in a chain:

  @(output :filter (:downcase (:fun foo_to_bar) :upcase))
  ...
  @(end)

Here is a split function which takes an extra argument.

  @(define split (in out sep))
  @  (next :list in)
  @  (coll)@(maybe)@token@sep@(or)@token@(end)@(end)
  @  (bind out token)
  @(end)

Furthermore, note that it produces a list rather than a string.
This function separates the argument in into tokens according to the
separator text sep.

Here is another function, join, which catenates a list:

  @(define join (in out sep))
  @  (output :into out)
  @  (rep)@in@sep@(last)@in@(end)
  @  (end)
  @(end)

Now here is these two being used in a chain:

  @(bind text "how,are,you")
  @(output :filter (:fun split ",") (:fun join "-"))
  @text
  @(end)

Output:

  how-are-you

When the filter invokes a function, it generates the first two arguments
internally to pass in the input value and capture the output. The remaining
arguments from the (:fun ...) construct are also passed to the function.
Thus the "," and "-" are passed as the sep argument to split and join.

Note that split puts out a list, which join accepts. So the overall filter
chain operates on a string: a string goes into split, and a string comes out of
join.

.SS The Deffilter Directive

The deffilter directive allows a query to define a custom filter, which
can then be used in @(output) clauses to transform substituted data.

This directive's syntax is illustrated in this example:

  Query:        @(deffilter rot13 
                   ("a" "n")
                   ("b" "o")
                   ("c" "p")
                   ("d" "q")
                   ("e" "r")
                   ("f" "s")
                   ("g" "t")
                   ("h" "u")
                   ("i" "v")
                   ("j" "w")
                   ("k" "x")
                   ("l" "y")
                   ("m" "z")
                   ("n" "a")
                   ("o" "b")
                   ("p" "c")
                   ("q" "d")
                   ("r" "e")
                   ("s" "f")
                   ("t" "g")
                   ("u" "h")
                   ("v" "i")
                   ("w" "j")
                   ("x" "k")
                   ("y" "l")
                   ("z" "m"))
                @(collect)
                @line
                @(end)
                @(output :filter rot13)
                @(repeat)
                @line
                @(end)
                @(end)

  Input:        hey there!

  Output:       url gurer!


The deffilter symbol must be followed by the name of the filter to be defined,
followed by forms which evaluate to lists of strings. Each list must
be at least two elements long and specifies one or more texts which are mapped
to a replacement text. For instance, the following specifies a telephone keypad
mapping from upper case letters to digits.
 
  @(deffilter alpha_to_phone ("E" "0") 
                             ("J" "N" "Q" "1")
                             ("R" "W" "X" "2")
                             ("D" "S" "Y" "3")
                             ("F" "T" "4")
                             ("A" "M" "5")
                             ("C" "I" "V" "6")
                             ("B" "K" "U" "7")
                             ("L" "O" "P" "8")
                             ("G" "H" "Z" "9"))

  @(deffilter foo (`@a` `@b`) ("c" `->@d`))

  @(bind x ("from" "to"))
  @(bind y ("---" "+++"))
  @(deffilter sub x y)

The last deffilter above equivalent to 
@(deffilter sub ("from" "to") ("---" "+++")).

Filtering works using a longest match algorithm. The input is scanned from left
to right, and the longest piece of text is identified at every character
position which matches a string on the left hand side, and that text is
replaced with its associated replacement text. The scanning then continues
at the first character after the matched text.

If none of the strings matches at a given character position, then that
character is passed through the filter untranslated, and the scan continues at
the next character in the input.

Filtering is not in-place but rather instantiates a new text, and so
replacement text is not re-scanned for more replacements.

If a filter definition accidentally contains two or more repetitions of the
same left hand string with different right hand translations, the later ones
take precedence. No warning is issued.


.SS The Filter Directive

The syntax of the filter directive is:

  @(filter FILTER { VAR }+ )

A filter is specified, followed by one or more variables whose values
are filtered and stored back into each variable.

Example: convert a, b, and c to upper case and HTML encode:

  @(filter (:upcase :to_html) a b c)

.SH EXCEPTIONS

.SS Introduction

The exceptions mechanism in
.B TXR
is another disciplined form of non-local transfer, in addition to the blocks
mechanism (see BLOCKS above).  Like blocks, exceptions provide a construct
which serves as the target for a dynamic exit.  Both blocks and exceptions
can be used to bail out of deep nesting when some condition occurs.
However, exceptions provide more complexity. Exceptions are useful for
error handling, and TXR in fact maps certain error situations to exception
control transfers. However, exceptions are not inherently an error-handling
mechanism; they are a structured dynamic control transfer mechanism, one
of whose applications is error handling.

An exception control transfer (simply called an exception) is always identified
by a symbol, which is its type. Types are organized in a subtype-supertype
hierarchy.  For instance, the file_error exception type is a subtype of the
error type. This means that a file error is a kind of error. An exception
handling block which catches exceptions of type error will catch exceptions of
type file_error, but a block which catches file_error will not catch all
exceptions of type error. A query_error is a kind of error, but not a kind of
file_error. The symbol t is the supertype of every type: every exception type
is considered to be a kind of t.  (Mnemonic: t stands for type, as in any
type).

Exceptions are handled using @(catch) clauses within a @(try) directive.

In addition to being useful for exception handling, the @(try) directive
also provides unwind protection by means of a @(finally) clause,
which specifies query material to be executed unconditionally when
the try clause terminates, no matter how it terminates.

.SS The Try Directive

The general syntax of the try directive is

  @(try)
  ... main clause, required ...
  ... optional catch clauses ...
  ... optional finally clause
  @(end)

A catch clause looks like:

  @(catch TYPE)
  .
  .
  .

and also the this form, equivalent to @(catch (t)):

  @(catch)
  .
  .
  .

which catches all exceptions.

A finally clause looks like:

  @(finally)
  ...
  .
  .

The main clause may not be empty, but the catch and finally may be.

A try clause is surrounded by an implicit anonymous block (see BLOCKS section
above). So for instance, the following is a no-op (an operation with no effect,
other than successful execution):

  @(try)
  @(accept)
  @(end)

The @(accept) causes a successful termination of the implicit anonymous block.
Execution resumes with query lines or directives which follow, if any.

Try clauses and blocks interact. For instance, a block accept from within
a try clause invokes a finally.

  Query:        @(block foo)
                @  (try)
                @    (accept foo)
                @  (finally)
                @     (output)
                bye!
                @     (end)
                @  (end)

  Output:       bye!

How this works: the try block's main clause is @(accept foo). This causes
the enclosing block named foo to terminate, as a successful match.
Since the try is nested within this block, it too must terminate
in order for the block to terminate. But the try has a finally clause,
which executes unconditionally, no matter how the try block
terminates. The finally clause performs some output, which is seen.

.SS The Finally Clause

A try directive can terminate in one of three ways. The main clause
may match successfully, and possibly yield some new variable bindings.
The main clause may fail to match. Or the main clause may be terminated
by a non-local control transfer, like an exception being thrown or a block
return (like the block foo example in the previous section).

No matter how the try clause terminates, the finally clause is processed.

Now, the finally clause is itself a query which binds variables, which leads to
the question: what happens to such variables? What if the finally block fails
as a query? Another question is: what if a finally clause itself initiates a
control transfer?  Answers follow.

Firstly, a finally clause will contribute variable bindings only if the main
clause terminates normally (either as a successful or failed match).
If the main clause successfully matches, then the finally block continues
matching at the next position in the data, and contributes bindings.
If the main clause fails, then the finally block matches at the
same position.

The overall try directive succeeds as a match if either the main clause
or the finally clause succeed. If both fail, then the try directive is
a failed match. The subquery in which it is located fails, et cetera.

Example:

  Query:        @(try)
                @a
                @(finally)
                @b
                @(end)
                @c

  Data:         1
                2
                3

  Output:       a=1
                b=2
                c=3

In this example, the main clause of the try captures line "1" of the data as
variable a, then the finally clause captures "2" as b, and then the
query continues with the @c variable after try block, and captures "3".


Example:

  Query:        @(try)
                hello @a
                @(finally)
                @b
                @(end)
                @c

  Data:         1
                2

  Output:       b=1
                c=2

In this example, the main clause of the try fails to match, because
the input is not prefixed with "hello ". However, the finally clause
matches, binding b to "1". This means that the try block is a successful
match, and so processing continues with @c which captures "2".

When finally clauses are processed during a non-local return,
they have no externally visible effect if they do not bind variables.
However, their execution makes itself known if they perform side effects,
such as output.

A finally clause guards only the main clause and the catch clauses. It does not
guard itself.   Once the finally clause is executing, the try block is no
longer guarded.  This means if a nonlocal transfer, such as a block accept
or exception, is initiated within the finally clause, it will not re-execute
the finally clause. The finally clause is simply abandoned.

The disestablishment of blocks and try clauses is properly interleaved
with the execution of finally clauses. This means that all surrounding
exit points are visible in a finally clause, even if the finally clause
is being invoked as part of a transfer to a distant exit point.
The finally clause can make a control transfer to an exit point which
is more near than the original one, thereby "hijacking" the control
transfer. Also, the anonymous block established by the try directive
is visible in the finally clause.

Example:

  @(try)
  @  (try)
  @    (next "nonexistent-file")
  @  (finally)
  @    (accept)
  @  (end)
  @(catch file_error)
  @  (output)
  file error caught
  @  (end)
  @(end)

In this example, the @(next) directive throws an exception of type file_error,
because the given file does not exist. The exit point for this exception is the
@(catch file_error) clause in the outer-most try block. The inner block is
not eligible because it contains no catch clauses at all. However, the inner
try block has a finally clause, and so during the processing of this
exception which is headed for the @(catch file_error), the finally
clause performs an anonymous accept. The exit point for the accept
is the anonymous block surrounding the inner try.  So the original
transfer to the catch clause is forgotten. The inner try terminates
successfully, and since it constitutes the main clause of the outer try,
that also terminates successfully. The "file error caught" message is
never printed.

.SS Catch Clauses

Catch clauses establish a try block as a potential exit point for
an exception-induced control transfer (called a ``throw'').

A catch clause specifies an optional list of symbols which represent
the exception types which it catches. The catch clause will catch
exceptions which are a subtype of any one of those exception types.

If a try block has more than one catch clause which can match a given
exception, the first one will be invoked.

When a catch is invoked, it is of course understood that the main clause did
not terminate normally, and so the main clause could not have produced any
bindings.

Catches are processed prior to finally.

If a catch clause itself throws an exception, that exception cannot
be caught by that same clause or its siblings in the same try block.
The catches of that block are no longer visible at that point.
Nevertheless, the catch clauses are still protected by the finally block.
If a catch clause throws, the finally block is still processed.

If a finally block throws an exception, then it is simply aborted;
the remaining directives in that block are not processed.

So the success or failure of the try block depends on the behavior of the catch
clause or the finally, if there is one. If either of them succeed, then the try
block is considered a successful match.

Example:

  Query:        @(try)
                @  (next "nonexistent-file")
                @  x
                @  (catch file_error)
                @a
                @(finally)
                @b
                @(end)
                @c

  Data:         1
                2
                3

  Output:       a=1
                b=2
                c=3

Here, the try block's main clause is terminated abruptly by a file_error
exception from the @(next) directive.   This is handled by the
catch clause, which binds variable a to the input line "1".
Then the finally clause executes, binding b to "2". The try block
then terminates successfully, and so @c takes "3".

.SS Catch Clauses with Parameters

A catch may have parameters following the type name, like this:

  @(catch pair (a b))

To write a catch-all with parameters, explicitly write the
master supertype t:

  @(catch t (arg ...))

Parameters are useful in conjunction with throw. The built-in
error exceptions generate one argument, which is a string containing
the error message. Using throw, arbitrary parameters can be passed
from the throw site to the catches.

.SS The Throw Directive

The throw directive generates an exception. A type must be specified,
followed by optional arguments. For example,

  @(throw pair "a" `@file.txt`)

throws an exception of type pair, with two arguments, being "a"
and the expansion of the quasiliteral `@file.txt`.

The selection of the target catch is performed purely using the type
name; the parameters are not involved in the selection.

Binding takes place between the arguments given in throw, and the
target catch.

If any catch parameter, for which a throw argument is given, is a bound
variable, it has to be identical to the argument, otherwise the catch fails.
(Control still passes to the catch, but the catch is a failed match).

  Query:        @(bind a "apple")
                @(try)
                @(throw e "banana")
                @(catch e (a))
                @(end)

  Output:       false

If any argument is an unbound variable, the corresponding parameter
in the catch is left alone: if it is an unbound variable, it remains
unbound, and if it is bound, it stays as is.

  Query:        @(try)
                @(trow e "honda" unbound)
                @(catch e (car1 car2))
                @car1 @car2
                @(end)

  Data:         honda toyota

  Output:       car1="honda"
                car2="toyota"

If a catch has fewer parameters than there are throw arguments,
the excess arguments are ignored.

  Query:         @(try)
                 @(throw e "banana" "apple" "pear")
                 @(catch e (fruit))
                 @(end)

  Output:        fruit="banana"

If a catch has more parameters than there are throw arguments, the excess
parameters are left alone. They may be bound or unbound variables.

  Query:        @(try)
                @(trow e "honda")
                @(catch e (car1 car2))
                @car1 @car2
                @(end)

  Data:         honda toyota

  Output:       car1="honda"
                car2="toyota"

A throw argument passing a value to a catch parameter which is unbound causes
that parameter to be bound to that value.

Throw arguments are evaluated in the context of the throw, and the bindings
which are available there. Consideration of what parameters are bound
is done in the context of the catch.

  Query:        @(bind c "c")
                @(try)
                @(forget c)
                @(bind (a c) ("a" "lc"))
                @(throw e a c)
                @(catch e (b a))
                @(end)

   Output:      c="c"
                b="a"
                a="lc"

In the above example, c has a toplevel binding to the string "c",
but is then unbound within the try construct, and rebound to the value "c".
Since the try construct is terminated by a throw, these modifications of the
binding environment are discarded. Hence, at the end of the query, variable
c ends up bound to the original value "c".  The throw still takes place
within the scope of the bindings set up by the try clause, so the values of
a and c that are thrown are "a" and "lc".  However, at the catch site, variable
a does not have a binding.  At that point, the binding to "a" established in
the try has disappeared already. Being unbound, the catch parameter a can take
whatever value the corresponding throw argument provides, so it ends up with
"lc".

.SS The Defex Directive

The defex directive allows the query writer to invent custom exception types,
which are arranged in a type hierarchy (meaning that some exception types are
considered subtypes of other types).

Subtyping means that if an exception type B is a subtype of A, then every
exception of type B is also considered to be of type A. So a catch for type A
will also catch exceptions of type B.  Every type is a supertype of itself: an
A is a kind of A. This of course implies that ever type is a subtype of itself
also.  Furthermore, every type is a subtype of the type t, which has no
supertype other than itself. Type nil is is a subtype of every type, including
itself.  The subtyping relationship is transitive also. If A is a subtype
of B, and B is a subtype of C, then A is a subtype of C.

Defex may be invoked with no arguments, in which case it does nothing:

  @(defex)

It may be invoked with one argument, which must be a symbol. This introduces a
new exception type. Strictly speaking, such an introduction is not necessary;
any symbol may be used as an exception type without being introduced by
@(defex):

  @(defex a)

Therefore, this also does nothing, other than document the intent to use
a as an exception.

If two or more argument symbols are given, the symbols are all introduced as
types, engaged in a subtype-supertype relationship from left to right.
That is to say, the first (leftmost) symbol is a subtype of the next one,
which is a subtype of the next one and so on. The last symbol, if it
had not been already defined as a subtype of some type, becomes a
direct subtype of the master supertype t. Example:

  @(defex d e)
  @(defex a b c d)

The fist directive defines d as a subtype of e, and e as a subtype of t.
The second defines a as a subtype of b, b as a subtype of c, and
c as a subtype of d, which is already defined as a subtype of e.
Thus a is now a subtype of e. It should be obvious that the above
could be condensed to:

  @(defex a b c d e)

Example:

  Query:        @(defex gorilla ape primate)
                @(defex monkey primate)
                @(defex human primate)
                @(collect)
                @(try)
                @(skip)
                @(cases)
                gorilla @name
                @(throw gorilla name)
                @(or)
                monkey @name
                @(throw monkey name)
                @(or)
                human @name
                @(throw human name)
                @(end)@#cases
                @(catch primate (name))
                @kind @name
                @(output)
                we have a primate @name of kind @kind
                @(end)@#output
                @(end)@#try
                @(end)@#collect


  Input:        gorilla joe
                human bob
                monkey alice

  Output:       we have a primate joe of kind gorilla
                we have a primate bob of kind human
                we have a primate alice of kind monkey

Exception types have a pervasive scope. Once a type relationship is introduced,
it is visible everywhere. Moreover, the defex directive is destructive,
meaning that the supertype of a type can be redefined. This is necessary so
that something like the following works right.

  @(defex gorilla ape)
  @(defex ape primate)

These directives are evaluated in sequence. So after the first one, the ape
type has the type t as its immediate supertype.  But in the second directive,
ape appears again, and is assigned the primate supertype, while retaining
gorilla as a subtype.  This situation could instead be diagnosed as an
error, forcing the programmer to reorder the statements, but instead
TXR obliges. However, there are limitations.  It is an error to define a
subtype-supertype relationship between two types if they are already connected
by such a relationship, directly or transitively. So the following
definitions are in error:

  @(defex a b)
  @(defex b c)
  @(defex a c)@# error: a is already a subtype of c, through b

  @(defex x y)
  @(defex y x)@# error: circularity; y is already a supertype of x.

.SH TXR LISP

The TXR language contains an embedded Lisp dialect called TXR Lisp.

This language is exposed in TXR in two ways.

Firstly, in any situation that calls for an expression, a Lisp compound
expression can be used, if it is preceded by the @ symbol. The Lisp expression
is evaluated and its value  becomes the value of that expression.
Thus, TXR directives are embedded in literal text using @, and Lisp expressions
are embedded in directives using @ also. 

Secondly, the @(do) directive can be used for evaluating one or more Lisp
forms, such that their value is thrown away. This is useful for evaluating some
Lisp code for the sake of its side effect, such as defining a variable,
updating a hash table, et cetera.

Examples:

Bind variable a to the integer 4:

  @(bind a @(+ 2 2))

Define several Lisp functions using @(do):

@(do 
  (defun add (x y) (+ x y))

  (defun occurs (item list)
    (cond ((null list) nil)
          ((atom list) (eql item list))
          (t (or (eq (first list) item)
                 (occurs item (rest list)))))))

.SS Overview

TXR Lisp is a small and simple dialect, like Scheme, but much more similar to
Common Lisp than Scheme. It has separate value and function binding namespaces,
like Common Lisp (and thus is a Lisp-2 type dialect), and represents boolean
true and false with the symbols t and nil (but note the case sensitivity of
identifiers denoting symbols!) Furthermore, the symbol nil is also the empty
list, which terminates nonempty lists.

Function and variable bindings are dynamically scoped in TXR Lisp. However,
closures do capture variables.

.SS Additional Syntax

Much of the TXR Lisp syntax has been introduced in the previous sections of the
manual, since directive forms are based on it. There is some additional syntax
that is useful in TXR Lisp programming.

.SS Quoting/Unquoting

.IP 'form

The quote character in front of a form is used for suppressing evaluation,
which is useful for forms that evaluate to something other than themselves.
For instance if '(+ 2 2) is evaluated, the value is the three-element list
(+ 2 2), wheras if (+ 2 2) is evaluated, the value is 4. Similarly, the
value of 'a is the symbol a itself, whereas the value of a is the value
of the variable a.

Note that TXR Lisp does not have a distinct quote and backquote syntax.
There is only one quote, which supports unquoting.

A quoted form which contains no unquotes codifies an ordinary quote.

A quoted form which contains unquotes expresses a quasiquote. (This should not
be confused with a string quasiliteral, although it is a related concept.)

.IP ,form

Thes comma character is used within a quoted list to denote an unquote.  Wheras
the quote suppresses evaluation, the comma introduces an exception: an element
of a form which is evaluated. For example, list '(a b c ,(+ 2 2)
(+ 2 2)) is the list (a b c 4 (+ 2 2)).  Everything
in the quote stands for itself, except for the ,(+ 2 2) which is evaluated.
The presence of ,(+ 2 2) in the quoted list turns it into a quasiquote.

.IP ,*form

The comma-star operator is used within a quoted list to denote a splicing unquote.
Wheras the quote suppresses evaluation, the comma introduces an exception: 
the form which follows ,* must evaluate to a list. That list is spliced into
the quoted list. For example: '(a b c ,*(list (+ 3 3) (+ 4 4) d)) evaluates
to (a b c 6 8 d).  The expression (list (+ 3 3) (+ 4 4)) is evaluated
to produce the list (6 8), and this list is spliced into the quoted template.

.IP ,'form

The comma-quote combination has a special meaning: the quote always
behaves as a regular quote and not a quasiquote, even if form contains
unquotes. Therefore, it does not "capture" these unquotes: they cannot
"belong" to this quote.  The comma and quote "cancel out", so the only effect
of comma-quote is to add one level of unquoting.  So for instance, whereas 
in '(a b c '(,d)), the subsitution of d belongs to the inner quote (it is
unquoted by the leftmost comma which belongs to the innermost quote) by
contrast, in '(a b c '(,',d)) the d is now one comma removed from the leftmost
comma and thus the substitution of d belongs to the outer quote. 
In other dialects of Lisp, this would be written `(a b c `(,',d)), making it
explicit which kind of quote is being specified. TXR Lisp works out which
kind of quote to use internally.

.IP ,*'form

The comma-splice form is analogous to comma-quote (see above).  Like in the
,' combination, in the ,*' combination, the quote behaves as a regular quote
and not a quasiquote.

.SS Quasiquoting non-List Objects

Quasiquoting is supported over hash table and vector literals (see Vectors
and Hashes below).  A hash table or vector literal can be quoted, like any
object, for instance:

  '#(1 2 3) ; value is #(1 2 3)

If unquotes occur in the vector, it is a quasivector.

  (let ((a 42))
    '#(1 ,a 3)) ; value is #(1 42 3)

The vector in the following example is also a quasivector. It contains
unquotes, and is though the quote is not directly applied to it,
it is surrounded in a quote.

  (let ((a 42))
    '(a b c #(d ,a))) ; value is (a b c #(d 42))

Hash table literals have two parts: the list of hash construction
arguments and the key-value pairs. For instance:

   #H((:equal-based) (a 1) (b 2))

where (:equal-based) is the list of arguments and the pairs are (a 1) and (b
2).  In quasiquoting, the arguments and pairs are treated as separate syntax;
it is not one big list.  So the following is not a possible way
to express the above hash:

  ;; not supported: splicing across the entire syntax
  (let ((hash-syntax '((:equal-based) (a 1) (b 2))))
    '#H(,*hash-syntax))

This is correct:

  ;; fine: splicing hash arguments and contents separatly
  (let ((hash-args '(:equal-based))
        (hash-contents '((a 1) (b 2))))
    '#H(,hash-args ,*hash-contents))

.SS Vectors

.IP "#(...)"

A hash token followed by a list denotes a vector. For example #(1 2 a)
is a three-element vector containing the numbers 1 and 2, and the symbol a.

.SS Hashes

.IP "#H((<hash-argument>*) (<key> <value>)*)"

The notation #H followed by a nested list syntax denotes a hash table literal.
The first item in the syntax is a list of keywords. These are the same
keywords as are used when calling the function hash to construct
a hash table. Allowed keywords are: :equal-based, :weak-keys, :weak-values.
An empty list can be specified as nil or (), which defaults to a
hash table basd on the eq function, with no weak semantics.

.SS Nested Quotes

Quotes can be nested.  What if it is necessary to unquote something in the
nested list? The following will not work in TXR Lisp like it does in
Common Lisp or Scheme: '(1 2 3 '(4 5 6 ,(+ 1 2))).  This is because the quote
is also "active" as a quasiquote, and so the ,(+ 1 2) belongs to the inner
quote, which protects it from evaluation. To get the (+ 1 2) value "through"
to the inner quote, the unquote syntax must also be nested using multiple
commas, like this: '(1 2 3 '(4 5 6 ,',(+ 1 2))). The leftmost comma goes
with the innermost quote.  The quote between the commas protects the (+ 1 2)
from repeated evaluations: the two unquotes call for two evaluations, but
we only want (+ 1 2) to be evaluated once.

.SS The .. notation

In TXR Lisp, there is a special "dotdot" notation consiting of a pair of dots.
This can be written between successive atoms or compound expressions, and is a
shorthand for cons.

That is to say, A .. B translates to (cons A B), and so for instance
(a b .. (c d) e .. f . g) means (a (cons b (c d)) (cons e f) . g).

This is a syntactic sugar useful in certain situations in which a cons is used
to represent a pair of numbers or other objects. For instance, if L
is a list, then [L 1 .. 3] computes a sublist of L consisting of
elements 1 through 2 (counting from zero).

.SS The DWIM Brackets

TXR Lisp has a square bracket notation. The syntax [...] is a shorthand
way of writing (dwim ...).  The [] syntax is useful for situations
where the expressive style of a Lisp-1 dialect is useful.

For instance if foo is a variable which holds a function object, then [foo 3]
can be used to call it, instead of (call foo 3).  If foo is a vector, then
[foo 3] retrieves the fourth element, like (vecref foo 3). Indexing over lists,
strings and hash tables is possible, and the notation is assignable.

Furthermore, any arguments enclosed in [] which are symbols are treated
according to a modified namespace lookup rule.

More details are given in the documentation for the dwim operator.

.SS Regular Expressions

In TXR Lisp, the / character can occur in symbol names, and the / token
is a symbol. Therefore the /regex/ syntax is absent, replaced with the
#/regex/ syntax.

.SH CONTROL FLOW AND SEQUENCING

When the first element of a compound expression is an operator symbol,
the interpretation of the meaning of that form is under the complete control
of that operator. The following sections list all of the operators available
in TXR Lisp.

In these sections Syntax is indicated using these conventions:

.TP
<word> 

A symbol in angle brackets denotes some syntactic unit: it
may be a symbol or compound form. The syntactic unit is explained
in the Description section.

.TP
{syntax}*  <word>*

This indicates a repetition of zero or more of the given
syntax enclosed in the braces or syntactic unit.

.TP
[syntax]  [<word>]

Square brackets indicate optional syntax.

.TP
alternative1 | alternative2 | ... | alternativeN

Multiple syntactic variations allowed in one place are
indicated as bar-separated items.

.SS Operators progn and prog1

.TP
Syntax:

  (progn <form>*)
  (prog1 <form>*)

.TP
Description

The progn operator evaluates forms in order, and returns the value
of the last form. The return value of (progn) is nil.

The prog1 operator evaluates forms in order, and returns the value
of the first form. The return value of (prog1) is nil.

Various other operators such as let also arrange for the evaluation
of a body of forms, the value of the last of which is returned.
These operators are said to feature an "implicit progn".

.SS Operator cond

.TP
Syntax:

  (cond {(<test> {form}*)}*)

.TP
Description:

The cond operator provides a multi-branching conditional evaluation of
forms. Enclosed in the cond form are groups of forms expressed as lists.
Each group must be a list of at least one form.

The forms are processed from left to right as follows: the first form,
<test>, in each group is evaluated. If it evaluates true, then the remaining
forms in that group, if any, are also evaluated. Processing then terminates and
the result of the last form in the group is taken as the result of cond.
If <test> is the only form in the group, then result of <test> is taken
as the result of cond.

If the first form of a group yields nil, then processing continues with the
next group, if any. If all form groups yield nil, then the cond form yields
nil.  This holds in the case that the syntax is empty: (cond) yields nil.

.SS Operator if

.TP
Syntax:

  (if <cond> <t-form> [<e-form>])

.TP
Description:

The if operator provides a simple two-way-selective evaluation control.
The <cond> form is evaluated. If it yields true then <t-form> is
evaluated, and that form's return value becomes the return value of the if.
If <cond> yields false, then <e-form> is evaluated and its return value
is taken to be that of if. If <e-form> is omitted, then the behavior is
as if <e-form> were specified as nil.

.SS Operator and

.TP
Syntax:

  (and {<form>}*)

.TP
Description:

The and operator provides three functionalities in one.  It computes the
logical "and" function over several forms.  It controls evaluation (a.k.a.
"short-circuiting").  It also allows the convenient substitution of an
arbitrary true value in the true case.

The and operator evaluates as follows. First, a return value is
established and initialized to the value t.  The forms, if any, are
evaluated from left to right.  The return value is overwritten with
the result of each form. Evaluation stops when all forms are exhausted,
or when any of them yields nil. When evaluation stops, the operator yields
the return value.

.TP
Examples:

  (and) -> t
  (and (> 10 5) (stringp "foo")) -> t
  (and 1 2 3) -> 3

.SS Operator or

.TP
Syntax:

  (or {<form>}*)

.TP
Description:

The and operator provides three functionalities in one.  It computes the
logical "or" function over several forms.  It controls evaluation (a.k.a.
"short-circuiting").  The behavior of or also provides for a simplified
selection of the first non-nil value from a sequence of forms.

The or operator evaluates as follows.  First, a return value is
established and initialized to the value nil. The forms, if any,
are evaluated from left to right. The return value is overwritten
with the result of each form. Evaluation stops when all forms are
exhausted, or when a form yields a true value. When evaluation stops, the
operator yields the return value.

.TP
Examples:

  (or) -> nil
  (or 1 2) -> 1
  (or nil 2) -> 2
  (or (> 10 20) (stringp "foo")) -> t

.SS Operator unwind-protect

.TP
Syntax:

  (unwind-protect <protected-form> <cleanup-form>*)

.TP
Description:

The unwind-protect operator evaluates <protected-form> in such a way that no
matter how the execution of <protected-form> terminates, the <cleanup-form>-s
will be executed.

The cleanup forms, however, are not protected. If a cleanup form terminates via
some non-local jump, the subsequent cleanup forms are not evaluated.

Cleanup forms themselves can "hijack" a non-local control transfer such
as an exception. If a cleanup form is evaluated during the processing of
a dynamic control transfer such as an exception, and that cleanup form
initiats its own dynamic control transfer, the original control transfer
is aborted and replaced with the new one.

.TP
Example:

    (block foo
      (unwind-protect
        (progn (return-from foo 42)
               (format t "not reached!\en"))
        (format t "cleanup!\n")))

In this example, the protected progn form terminates by returning from
block foo. Therefore the form does not complete and so the
output "not reached!" is not produced. However, the cleanup form
excecutes, producing the output "cleanup!".

.SS Operator block

.TP
Syntax:

  (block <name> <body-form>*)

.TP
Description:

The block operator introduces a named block around the execution of
some forms. The <name> argument must be a symbol. Since a block name is not
a variable binding, keyword symbols are permitted, and so are the symbols
t and nil.   A block named by the symbol nil is slighlty special: it is
understood to be an anonymous block.

Blocks in TXR Lisp have dynamic scope. This means that the following
situation is allowed:

  (defun func () (return-from foo 42))
  (block foo (func))

The function can return from the foo block even though the foo block
does not lexically surround foo.

Thus blocks in TXR Lisp provide dynamic non-local returns, as well
as returns out of lexical nesting.

.TP
Dialect Note:

In Common Lisp, blocks are lexical. A separate mechanism consisting of
catch and throw operators performs non-local transfer based on symbols.
The TXR Lisp example:

  (defun func () (return-from foo 42))
  (block foo (func))

is not allowed in Common Lisp, but can be transliterated to:

  (defun func () (throw 'foo 42))
  (catch 'foo (func))

Note that foo is quoted in CL. This underscores the dynamic nature of
the construct. THROW itself is a function and not an operator.

.SS Operators return, return-from

.TP
Syntax:

  (return [<value>])
  (return-from <name> [<value>])

.TP
Description:

The return operator must be dynamically enclosed within an anonymous
block (a block named by the symbol nil). It immediately terminates the
evaluation of the innermost anonyous block which encloses it, causing
it to return the specified value. If the value is omitted, the anonymous
block returns nil.

The return-from operator must be dynamically enclosed within a named block
whose name matches the <name> argument. It immediately terminates the
evaluation of the innermost such block, causing it to return the specified
value. If the value is omitted, that block returns nil.

.TP
Example:

    (block foo
      (let ((a "abc\n")
            (b "def\n"))
        (pprint a *stdout*)
        (return-from foo 42)
        (pprint b *stdout*)))

Here, the output produced is "abc". The value of b is not printed
because the return-from terminates block foo, and so the second pprint
form is not evaluated.

.SH EVALUATION

.SS Operator dwim

.TP
Syntax:

  (dwim <argument>*)

  [<argument>*]

.TP
Description:

The dwim operator's name is an acronym: DWIM may be taken to mean
"Do What I Mean", or alternatively, "Dispatch, in a Way that is
Intelligent and Meaningful".

The notation [...] is a shorthand equivalent to (dwim ...) and is the preferred
way for writing dwim expressions.

The dwim operator takes a variable number of arguments, which are
all evaluated in the same way: the first argument is not evaluated different
from the remaining arguments. 

Furthermore, the evaluation of symbols is done differently: all of the
enclosing scopes are considered as if the function and variable namespaces are
collapsed into a single namespace, in which variable names take precedence over 
functions if there exist mutiple bindings. This allows functions to be
referenced without the fun operator.

All forms which are not symbols are evaluated using the normal evaluation rules.

The first argument may not be an operator such as let, et cetera. 

How many are required depends on the type of object to which the first argument
expression evaluates: of the first argument.  The possibilities are:

.IP "[<function> <argument>*]"
Call the given the function object to the given arguments.

.IP "[<symbol> <argument>*]"
If the first expression evaluates to a symbol, that symbol
is resolved in the function namespace, and then
the resulting function, if found, is called with the
given arguments.

.IP "[<list> <index>]"
Retrieve the specified element from the specified list. Index zero
refers to the first element. Indexed list access does not throw exceptions.
Negative indices yield nil, and indices beyond the end of a list
yield nil. (However assignment to a nonexistent list element throws.)

.IP "[<list> <from-index>..<to-below-index>]"
Retrieve the specified range of elements, exactly as if
using (sub-list <list> <from-index> <to-below-index>).
The range of elements is specified in the car and cdr fields of a cons cell,
for which the .. (dotdot) syntactic sugar is useful.
See the section on Indexing below.

.IP "[<vector> <index>]"
Retrieve the specified element of a vector. This is equivalent to
(vecref <vector> <index>).

.IP "[<vector> <from-index>..<to-below-index>]"
Retrieve the specified range of elements, exactly as if
using (sub-vec <list> <from-index> <to-below-index>).
The range of elements is specified in the car and cdr fields of a cons cell,
for which the .. (dotdot) syntactic sugar is useful.
See the section on Range Indexing below.

.IP "[<string> <index>]"
Retrieve the specified element of a string. This is equivalent to
(chr-str <string> <index>).

.IP "[<string> <from-index>..<to-below-index>]"
Retrieve the specified range of characters from the string, exactly as if
using (sub-str <string> <from-index> <to-below-index>).
The range of elements is specified in the car and cdr fields of a cons cell,
for which the .. (dotdot) syntactic sugar is useful.
See the section on Indexing below.

.IP "[<hash-table> <key> <default-value>]"
Retrieve a value from the hash table corresponding to <key>,
or <default-value> if there is no such entry.

The first argument may not be an operator such as let, only a function.

The places denoted by the dwim operator can be assigned.  There are some
restrictions. List, string and vector ranges can only be replaced using
the set operator. The other operators like push do not apply.  
Characters in a string can only be assigned with set or incremented with inc
and dec.

The source of a range assignment can be a string, vector or list,
regardless of whether the target is a string, vector or list.
If the target is a string, the replacement sequence must be
a string, or a list or vector of characters.

.TP
Range Indexing

Vector and list range indexing is based from zero. The first element element
zero. Furthermore, the value -1 refers to the last element of the vector or
list, and -2 to the second last and so forth. So the range 1 .. -2 means
"everything except for the first element and the last two".

The symbol t represents the position one past the end of the vector, string or
list, so 0 .. t denotes the entire list or vector, and the range t .. t
represents the empty range just beyond the last element.
It is possible to assign to t .. t. For instance:

  (defvar list '(1 2 3))
  (set [list t .. t] '(4)) ;; list is now (1 2 3 4)

Either end of the range can also be specified as nil. If the start is specified
as nil, it means zero. If the end is specified as nil, it means one element
past the end. Thus nil .. nil spans all of the elements.

The value zero has a "floating" behavior when used as the end of a range.
If the start of the range is a negative value, and the end of the
range is zero, the zero is interpreted as being the position past the
end of the sequence, rather than the first element. For instance the range
-1..0 means the same thing as -1..t or -1..nil. Zero at the start of a range
always means the first element, so that 0..-1 refers to all the elements except
for the last one.

.TP
Notes:

The dwim operator allows for a Lisp-1 flavor of programming in TXR Lisp,
which is normally Lisp-2, with some useful extensions.

A Lisp-1 dialect is one in which an expression like (a b) treats both a and b
as expressions with the same evaluation rules. The symbols a and b are looked
up in a variable namespace. A function call occurs if the value of variable
a is a function object.  Thus in a Lisp-1, named functions do not exist as
such: they are just variable bindings.  In a Lisp-1 (car 1 2) means that there
is a variable called car, which holds a function. In a Lisp-2 (car 1 2) means
that there is a function called car, and so (car car car) is possible, because
there can be also a variable called car.

The Lisp-1 design has certain disadvantages, which are avoided in TXR Lisp by
confining the Lisp-1 expressivity inside the [...] notation, in which operators
are not allowed.  When round parentheses are used, the normal Lisp-2 rules
apply. A "best of both worlds" situation is achieved. The square brackets
are just as convenient as parentheses and at the same time visually distinct,
making it clear that different rules apply.

The Lisp-1 is useful for functional programming, because it eliminates
occurences of the call and fun operators.  For instance:

  ;; regular notation

  (funcall foo (fun second) '((1 a) (2 b)))

  ;; [] notation

  [foo second '((1 a) (2 b))]

Lisp-1 dialects can also provide useful extensions by giving a meaning
to objects other than functions in the first position of a form,
and the dwim/[...] syntax does exactly this.
However, unlike Lisp-1 dialects, the [] syntax does not allow operators.
It
.B is
an operator: (dwim ...).


.SS Function identity

.TP
Syntax:

  (identity <value>)

.TP
Description:

The identity function returns its argument. 

.TP
Notes:

The identify function is useful as a functional argument, when a transformation
function is required, but no transformation is actually desired.

.SS Function eval

.TP
Syntax:

  (eval <form> <env>)

.TP
Description:

The eval function treats the <form> object as a Lisp expression, which is
evaluated. The side effects implied by the form are performed, and the value
which it produces is returned. The <env> object specifies an environment for
resolving the function and variable references encountered in the expression.
The object nil can be specified as an environment, in which case the evaluation
takes place in the top-level environment.

.SH MUTATION

.SS Operators inc, dec, set, push, pop, flip and del

.TP
Syntax:

  (inc <place> [<delta>])
  (dec <place> [<delta>])
  (set <place> <new-value>)
  (push <item> <place>)
  (pop <place>)
  (flip <place>)
  (del <place>)

.TP
Description:

These destructive operators update the value of a place. A place is a storage
location which is denoted by a form. Place forms are identical to value
accessing forms. That is to say, any form recognized as a place by these
operators can be evaluated by itself to retrieve the value of the storage
location. However, the converse is false: not all forms which access storage
location are recognized as places.

With are exceptions noted below, it is an error if a place does not exist.
For instance, a variable being assigned must exist.

Literal objects which are directly specified in the source code are
considered part of the program body. Modifying parts of these objects
therefore gives rise to self-modifying code. The behavior of self-modifying
code is not specified.

The inc and dec update the place by adding or subtracting, respectively, a
displacement to or from that number. If the <delta> expression is
specified, then it is evaluated and its value is used as the increment.
Otherwise, a default increment of 1 is used. The prior value of the place
and the delta must be suitable operands for the + and - functions.
(inc x) is equivalent to (set x (+ 1 x)), except that expression x
is evaluated only once to determine the storage location. The inc
and dec operators return the new value that was stored.

The set operator overwrites the previous value of a place with a new value,
and also returns that value.

The push and pop operators operate on a place which holds a list.  The push
operator updates the list by replacing it with a new list which has a new item
at the front, followed by the previous list. The item is returned.
The pop operator performs the reverse operation: it removes the first item
from the list and returns it. (push y x) is similar to

  (let ((temp y)) (set x (cons temp x)) temp)

except that x is evaluated only once to determine the storage place, and no
such temporary variable is visible to the program.  Similarly, (pop x) is much
like

  (let ((temp (car x))) (set x (cdr x)) temp)
 
except that x is evaluated only once, and no such temporary variable
is visible to the program.

The flip operator toggles a place between true and false. If the place
contains a value other than nil, then its value is replaced with nil.
If it contains nil, it is replaced with t.

The del operator does not modify the value of a place, but rather deletes the
place itself. Index values and ranges of lists denoted using the dwim operator
indexing notation can be subject to a deletion, as can hash table entries
denoted using dwim or gethash. It is an error to try to delete other kinds of
places such as simple variables. The del operator returns the value of the
place that was deleted. Deleting from a sequence means removing the element or
elements. Deleting a hash place means removing the corresponding entry from the
hash table.

Currently, these forms are recognized as places:

  <symbol>

  (car <cons>)

  (cdr <cons>)

  (gethash <hash> <key> <default-value>)

  (vecref <vector> <index>)

  (dwim <obj> ...)
  
  [<obj> ...]  ;; equivalent to (dwim <obj> ...)


A <symbol> place denotes a variable. If the variable does not exist, it is an
error. 

The (car <form>) and (cdr <form>) places denote the corresponding slots
of a cons cell. The <cons> form must be an expression which evaluates to a
cons. 

The gethash place denotes a value stored in a hash table.
The form <hash> must evaluate to a hash table. If the place does not exist
in the hash table under the given key, then the destructive operation
will create it. In that case, the <default-value> form is evaluated to
determine the initial value of the place. Otherwise it is ignored.

The vecref place denotes a vector element, allowing vector elements
to be treated as assignment places.

The dwim/[] place denotes a vector element, list element, string, or hash
table, depending on the type of obj. 

.SH BINDING AND ITERATION

.SS Operators let and let*

.TP
Syntax:

  (let ({<sym> | (<sym> <init-form>)}*) <body-form>*)
  (let* ({<sym> | (<sym> <init-form>)}*) <body-form>*)

.TP
Description:

The let and let* operators introduce a new scope with variables and
evaluate forms in that scope. The operator symbol, either let or let*,
is followed by a list which can contain any mixture of variable
name symbols, or (<sym> <init-form>) pairs.  A symbol
denotes the name of variable to be instantiated and initialized
to the value nil.  A symbol specified with an init-form denotes
a variable which is intialized from the value of the init-form.

The symbols t and nil may not be used as variables, and neither
can be keyword symbols: symbols denoted by a leading colon.

The difference between let and let* is that in let*, later init-forms
have visibility over the variables established by earlier variables
in the same let* construct. In plain let, the variables are not
visible to any of the init-forms.

When the variables are established, then the body forms
are evaluated in order. The value of the last form becomes the
return value of the let. 

If the forms are omitted, then the return value nil is produced.

The variable list may be empty.


.TP
Examples:

  (let ((a 1) (b 2)) (list a b)) -> (1 2)
  (let* ((a 1) (b (+ a 1))) (list a b (+ a b))) -> (1 2 3)
  (let ()) -> nil
  (let (:a nil)) -> error, :a and nil can't be used as variables

.SS Operators for and for*

.TP
Syntax:

  ({for | for*} ({<sym> | (<sym> <init-form>)}*) 
                (<test-form> <result-form>*) 
                (<inc-form>*)
    <body-form>*)

.TP
Description:

The for and for* operators combine variable binding with loop iteration.
The first argument is a list of variables with optional initializers,
exactly the same as in the let and let* operators. Furthermore, the
difference between for and for* is like that between let and let* with
regard to this list of variables. 
The for operators execute these steps:

1. Establish bindings for the specified variables similarly to let
and let*. The variable bindings are visible over the <test-form>, each
<result-form>, each <inc-form> and each <body-form>.

2. Establish an anonymous block over the remaining forms, allowing
the return operator to be used to terminate the loop.

3. Evaluate <test-form>. If <test-form> yields nil, then each
<result-form> is evaluated, and the vale of the last of these forms
is is the result value of the for loop. If there are no such forms
then the return value is nil.

4. Otherwise, if <test-form> yields non-nil, then each <body-form>
is evaluated in turn. Then, each <inc-form> is evaluated in turn
and processing resumes at step 2.

Furthermore, the for operators establish an anonymous block,
allowing the return operator to be used to terminate at any point.

.SS Operators each, each*, collect-each and collect-each*

.TP
Syntax:

  (each ({(<sym> <init-form>)}*) <body-form>*)
  (each* ({(<sym> <init-form>)}*) <body-form>*)
  (collect-each ({(<sym> <init-form>)}*) <body-form>*)
  (collect-each* ({(<sym> <init-form>)}*) <body-form>*)

.TP
Description:

These operator establish a loop for iterating over the elements of one or more
lists. Each <init-form> must evaluate to a list. The lists are then iterated in
parallel over repeated evaluations of the <body-form>-s, which each <sym>
variable being assigned to successive elements of its list. The shortest list
determines the number of iterations, so if any of the <init-form>-s evaluate to
an empty list, the body is not executed.

The body forms are enclosed in an anonymous block, allowing the return
operator to terminate the looop prematurely and optionally specify
the return value.

The collect-each and collect-each* variants are like each and each*,
except that for each iteration, the resulting value of the body is collected
into a list. When the iteration terminates, the return value is this
collection.

The alternate forms denoted by the adorned symbols each* and collect-each*
variants differ from each and collect-each in the following way. The plain
forms evaluate the <init-form>-s in an environment in which none of the <sym>
variables are yet visible. By contrast, the alternate forms evaluate each
<init-form> in an environment in which bindings for the previous <sym>
variables are visible.  In this phase of evaluation, <sym> variables are
list-valued: one by one they are each bound to the list object emanating from
their corresponding <init-form>. Just before the first loop iteration, however,
the <sym> variables are assigned the first item from each of their lists.

.TP
Examples:

 ;; print numbers from 1 to 10 and whether they are even or odd
 (each* ((n (range 1 10)) 
         (even (collect-each ((n m)) (evenp m)))) ;; n is a list here
   (format t "~s is ~s\n" n (if even "even" "odd"))) ;; n is an item here

 Output:

 1 is odd
 2 is even
 3 is odd
 4 is even
 5 is odd
 6 is even
 7 is odd
 8 is even
 9 is odd
 10 is even

.SH FUNCTION OBJECTS AND NAMED FUNCTIONS

.SS Operator defun

.TP
Syntax:

  (defun <name> ({<param> [. <rest-param>]}*) <body-form>*)

Description:

The defun operator introduces a new function in the global function namespace.
The function is similar to a lambda, and has the same parameter syntax
and semantics as the lambda operator.

Unlike in lambda, the <body-form>-s of a defun are surrounded by a block.
The name of this block is the same as the name of the function, making it
possible to terminate the function and return a value using (return-from <name>
<value>). For more information, see the definition of the block operator.

A function may call itself by name, allowing for recursion.

.SS Operator lambda

.TP
Syntax:

  (lambda ({<sym>}*[. <sym>]) {<body-form>}*)

  (lambda <sym> {<body-form>}*)

.TP
Description:

The lambda operator produces a value which is a function.  Like in most other
Lisps, functions are objects in TXR Lisp.  They can be passed to functions as
arguments, returned from functions, aggregated into lists, stored in variables,
et cetera.

The first argument of lambda is the list of parameters for the function.   It
may be empty, and it may also be an improper list (dot notation) where the
terminating atom is a symbol other than nil. It can also be a single symbol.

The second and subsequent arguments are the forms making up the function body.
The body may be empty.

When a function is called, the parameters are instantiated as variables that
are visible to the body forms. The variables are initialized from the values of
the argument expressions appearing in the function call.

The dotted notation can be used to write a function that accepts
a variable number of arguments. To write a function that accepts
variable arguments only, with no required arguments, use a single symbol.

The keyword symbol : can appear in the parameter list. It is not an argument,
but a separator between required parameters and optional parameters.
When the function is called, optional parameter for which arguments
are not supplied take on the value nil.

Functions created by lambda capture the surrounding variable bindings.


.TP
Examples:

Counting function. This function, which takes no arguments, captures the
variable "counter". Whenever this object is called, it increments the counter
by 1 and returns the incremented value.

  (let ((counter 0))
    (lambda () (inc counter)))

Function that takes two or more arguments. The third and subsequent arguments
are aggregated into a list passed as the single parameter z:

  (lambda (x y . z) (list 'my-arguments-are x y z))

Variadic funcion:

  (lambda args (list 'my-list-of-arguments args))

Optional arguments:

  [(lambda (x : y) (list x y)) 1] -> (1 nil)
  [(lambda (x : y) (list x y)) 1 2] -> (1 2)

.SS Operator call

.TP
Syntax:

  (call <function-form> {<argument-form>}*)

.TP
Description:

The call operator invokes a function. <function-form> must evaluate
to a function. Each <argument-form> is evaluated in left to right
order and the resulting values are passed to the function as arguments.
The return value of the (call ...) expression is that of the function
applied to those arguments.

The <function-form> may be any Lisp form that produces a function
as its value: a symbol denoting a variable in which a function is stored,
a lambda expression, a function call which returns a function,
or (fun ...) expression.

.TP
Examples:

Apply arguments 1 2 to a lambda which adds them to produce 3:

(call (lambda (a b) (+ a b)) 1 2) -> 3

Useless use of call on a named function; equivalent to (list 1 2):

(call (fun list) 1 2) -> (1 2)

.SS Operator fun

.TP
Syntax:

  (fun <function-name>)

.TP
Description:
The fun operator retrieves the function object corresponding to a named
function.
. The <function-name> is a symbol denoting a named function: a built in
function, or one defined by defun.

.TP
Dialect Note:
A lambda expression is not a function name in TXR Lisp. The 
syntax (fun (lambda ...)) is invalid.

.SS Function symbol-function

.TP
Syntax:

  (symbol-function <symbol>)

.TP
Description:

The symbol-function retrieves the toplevel function binding of the given
symbol if it has one. If the symbol has no toplevel function binding,
the value nil is returned.

.TP
Dialect note:

The symbol-function form is currently not an assignable place. Only
the defun operator defines functions.

.SS Function func-get-form

.TP
Syntax:

  (func-get-form <func>)

.TP
Description:

The func-get-form function retrieves a source code form of <func>, which
must be an interpreted function. The source code form has the syntax 
(<name> <arglist> {<body-form>}*).

.SS Function func-get-env

.TP
Syntax:

  (func-get-env <func>)

.TP
Description:

The func-get-env function retrieves the environment object associated with
function <func>.  The environment object holds the captured bindings of a
lexical closure.

.SS Function functionp

.TP
Syntax:

  (functionp <obj>)

.TP
Description:

The functionp function returns t if <obj> is a function, otherwise it
returns nil.

.SS Function interp-fun-p

.TP
Syntax:

  (interp-fun-p <obj>)

.TP
Description:

The interp-fun-p function returns t if <obj> is an interpreted function,
otherwise it returns nil.

.SH OBJECT TYPE AND EQUIVALENCE

.SS Function typeof

.TP
Syntax:

  (typeof <value>)

.TP
Description

The typeof function returns a symbol representing the type of <value>.

.RS

The core types are identified by the following symbols.
.IP cons

A cons cell.

.IP str

String.

.IP lit

A literal string embedded in the TXR executable image.

.IP chr

Character.

.IP fixnum

Fixnum integer. An integer that fits into the value word, not having to
be heap allocated.

.IP sym

Symbol.

.IP pkg

Symbol package.

.IP fun

Function.

.IP vec

Vector.

.IP lcons

Lazy cons.

.IP lstr

Lazy string.

.IP env

Function/variable binding environment.

.IP bignum

A bignum integer: arbitrary precision integer that is heap-allocated.

.PP
There are additional kinds of objects, such as streams.

.SS Functions null and not

.TP
Syntax:

  (null <value>)
  (not <value>)

.TP
Description:

The null and not functions are synonyms.  They tests whether <value> is the
object nil. They return t if this is the case, nil otherwise.

.TP
Examples:

  (null '()) -> t
  (null nil) -> t
  (null ()) -> t

  (if (null x) (format t "x is nil!"))

  (let ((list '(b c d)))
    (if (not (memq 'a list))
      (format t "list ~s does not contain the symbol a\en")))

.SS Functions eq, eql and equal

.TP
Syntax:

  (eq <left-obj> <right-obj>)
  (eql <left-obj> <right-obj>)
  (equal <left-obj> <right-obj>)

.TP
Description:

The principal equality test functions eq, eql and equal test whether
two objects are equivalent, using different criteria. They return t
if the objects are equivalent, and nil otherwise.

The eq function uses the strictest equivalence test, called implementation
equality.  The eq function returns t if, and only if, <left-obj> and
<right-obj> are actually the same object. The eq test is is implemented
by comparing the raw bit pattern of the value, whether or not it is
an immediate value or a pointer to a heaped object, including its type
tags.  Consequently, two objects of different type are never equal, two
character values are eq if they are the same character, and two fixnum integers
are eq if they have the same value.  All other objects kinds are actually
represented as pointers, and are eq if they point to the same object in memory.
So two bignum integers might not be eq even if they have the same numeric
value, two lists might not be eq even if all their corresponding elements are
eq, two strings might not be eq even if they hold identical text, etc.

The eql function is slightly less strict than eq. The difference between
eql and eq is that if <left-obj> and <right-obj> are bignums which have
the same numeric value, eql returns t, even if they are different objects.
For all other objects, eql behaves like eq.

The equal function is less strict than eql. In general, it recurses into some
kinds of aggregate objects to perform a structural equivalence.  If <left-obj>
and <right-obj> are eql then they are also equal.  If the two objects are both
cons cells, then they are equal if their "car" fields are equal and their "cdr"
fields are equal.  If two objects are vectors, they are equal if they have the
same length, and their corresponding elements are equal.  If two objects are
strings, they are equal if they are textually identical.  If two objects are
functions, they are equal if they have equal environments, and if they have
equal functions. Two compiled functions are the same if they are the same
function. Two interpreted functions are equal if their list structure is equal.

For some aggregate objects, there is no special semantics.  Two hashes,
symbols, packages, or streams are equal if they are the same hash.

Certain object types have a custom equal function.

.SH BASIC LIST LIBRARY

When the first element of a compound form is a symbol denoting a function,
the evaluation takes place as follows. The remaining forms, if any, denote
the arguments to the function. They are evaluated in left to right order
to produce the argument values, and passed to the function.
An exception is thrown if there are not enough arguments, or too many.

Programs can define named functions with the defun operator

The following are Lisp functions and variables built-in to TXR.

.SS Function cons

.TP
Syntax:

  (cons <car-value> <cdr-value>)

.TP

Description:

The cons function allocates, intializes and returns a single cons cell.
A cons has two fields called "car" and "cdr", which are accessed by
functions of the same name, or by the functions "first" and "rest",
which are alternative spellings.

Lists are made up of conses. A (proper) list is either the symbol nil
denoting an empty list, or a cons cell which holds the first item of
the list in its "car", and the list of the remaining items in "cdr".
(cons 1 nil) allocates a one element list denoted (1). The "cdr"
is nil, so there are no additional items.

A cons cell with a "cdr" other than nil is printed with the dotted
pair notation. For example (cons 1 2) yields (1 . 2). 
The notation (1 . nil) is valid as input into the machine,
but is printed as (1). 

A list terminated by an atom other than nil is called an improper
list, and the dot notation is extended to cover improper lists.
For instance (1 2 . 3) is an improper list of two elements,
terminated by 3, and can be constructed using (cons 1 (cons 2 3)).
Another notation for this list is (1 . (2 . 3))
The list (1 2) is (1 . (2 . nil)).

.SS Function atom

.TP
Syntax:
(atom <value>)

.TP
Description:

The atom function tests whether <value> is an atom. It returns t if this is the
case, nil otherwise.  All values which are not cons cells are atoms.

(atom x) is equivalent to (not (consp x)).

.TP
Examples:

  (atom 3) -> t
  (atom (cons 1 2)) -> nil
  (atom "abc") -> t
  (atom '(3)) -> nil

.SS Function consp

.TP
Syntax:

(consp <value>)

.TP
Description:

The atom function tests whether <value> is a cons. It returns t if this is the
case, nil otherwise.

(consp x) is equivalent to (not (atom x)).

Non-empty lists test positive under consp because a list is represented
as a reference to the first cons in a chain of one or more conses.

.TP
Examples:

  (consp 3) -> nil
  (consp (cons 1 2)) -> t
  (consp "abc") -> nil
  (consp '(3)) -> t

.SS Functions car and first

.TP
Syntax:

  (car <cons-or-nil>)
  (first <cons-or-nil>)

.TP
Description:

The functions car and first are synonyms. They retrieve the "car"
field of a cons cell. (car (cons 1 2)) yields 1.

For programming convenience, (car nil) is allowed, and returns nil,
even though nil isn't a cons and doesn't have a "car" field.

.SS Functions cdr and rest

.TP
Syntax:

  (cdr <cons-or-nil>)
  (rest <cons-or-nil>)

.TP
Description:

The functions cdr and rest are synonyms. They retrieve the "cdr"
field of a cons cell. (cdr (cons 1 2)) yields 2.

For programming convenience, (cdr nil) is allowed, and returns nil,
even though nil isn't a cons and doesn't have a "cdr" field.

.TP
Example:

Walk every element of the list (1 2 3):

    (for ((i '(1 2 3))) (i) ((set i (cdr i)))
      (print (car i) *stdout*)
      (print #\enewline *stdout*))

The variable i marches over the cons cells which make up the "backbone"
of the list. The elements are retrieved using the car function.
Advancing to the next cell is achieved using (cdr i). If i is the
last cell in a (proper) list, (cdr i) yields nil. The guard
expression i fails and the loop terminates.

.SS Functions rplaca and rplacd

.TP
Syntax:

  (rplaca <cons> <new-car-value>)
  (rplacd <cons> <new-cdr-value>)

.TP
Description:

The rplaca and rplacd functions assign new values into the "car"
and "cdr" fields of the cell <cons>.  Note that (rplaca x y)
is the same as the more generic (set (car x) y), and likewise
(rplacd x y) can be written as (set (cdr x) y).

It is an error if <cons> is not a cons or lazy cons. In particular,
whereas (car nil) is correct, (rplaca nil ...) is erroneous.

.SS Functions second, third, fourth, fifth and sixth

.TP
Syntax:

  (first <list>)
  (second <list>)
  (third <list>)
  (fourth <list>)
  (fifth <list>)
  (sixth <list>)

.TP
Description:

These functions access the elements of a proper list by position.

If the list is shorter than implied, these functions return nil.

.TP
Examples:

  (third '(1 2)) -> nil
  (second '(1 2)) -> 2
  (third '(1 2 . 3)) -> **error**

.SS Functions append and append*

.TP
Syntax:

(append [<list>* <last-arg>])
(append* [<list>* <last-arg>])

.TP
Description:

The append function creates a new list which is a catenation of the
<list> arguments. All arguments are optional, such that (append) produces
the empty list.

If a single argument is specified, then append simply returns the value of that
argument. It may be any kind of object.

If N arguments are specified, where N > 1, then the first N-1 arguments must be
proper lists. Copies of these lists are catenated together. The last argument
N, shown in the above syntax as <last-arg>, may be any kind of object. It is
installed into the cdr field of the last cons cell of the resulting list.
Thus, if argument N is also a list, it is catenated onto the resulting list,
but without being copied. Argument N may be an atom other than nil; in that
case append produces an improper list.

The append* function works like append, but returns a lazy list which produces
the catenation of the lists on demand.  If some of the arguments are
themselves lazy lists which are infinite, then append* can return immediately,
whereas append will get caught in an infinite loop trying to produce a
catenation and eventually exhaust available memory. (However, the last
argument to append may be an infinite lazy list, because append does not
traverse the last argument.)

.TP
Examples:

  ;; An atom is returned.
  (append 3) -> 3

  ;; A list is also just returned: no copying takes place.
  ;; The eq function can verify that the same object emerges
  ;; from append that went in.
  (let ((list '(1 2 3))) 
    (eq (append list) list)) -> t

  (append '(1 2 3) '(4 5 6) 7) -> '(1 2 3 4 5 6 . 7))

  ;; the (4 5 6) tail of the resulting list is the original
  ;; (4 5 6) object, shared with that list.

  (append '(1 2 3) '(4 5 6)) -> '(1 2 3 4 5 6)

  (append nil) -> nil

  ;; (1 2 3) is copied: it is not the last argument
  (append '(1 2 3) nil) -> (1 2 3)

  ;; empty lists disappear
  (append nil '(1 2 3) nil '(4 5 6)) -> (1 2 3 4 5 6)
  (append nil nil nil) -> nil

  ;; atoms and improper lists other than in the last position
  ;; are erroneous
  (append '(a . b) 3 '(1 2 3)) -> **error**

.SS Function list

.TP
Syntax:

(list <value>*)

.TP
Description:

The list function creates a new list, whose elements are the
argument values.

.TP
Examples:

  (list) -> nil
  (list 1) -> (1)
  (list 'a 'b) -> (a b)

.SS Function sub-list

.TP
Syntax:

  (sub-list <list> [<from> [<to>]])

.TP
Description:

The sub-list function extracts a sublist from <list>. It is exactly like the
more generic function sub, except that it operates only on lists.
For a description of the arguments and semantics, refer to the sub function.

.SS Function replace-list

.TP
Syntax:

  (replace-list <list> <item-sequence> [<from> [<to>]])

.TP
Description:

The replace-list function replaces a subrange of <list> with items from
the item-sequence argument, which may be any kind of sequence (list, vector
or string).

It is like the replace function, except that the first argument must be
a list.

For a description of the arguments and semantics, refer to the replace function.

.SS Functions listp and proper-listp

.TP
Syntax:

  (listp <value>)
  (proper-listp <value>)

.TP
Description:

The listp and proper-listp functions test, respectively, whether
<value> is a list, or a proper list, and return
t or nil accordingly.

The listp test is weaker, and executes without having to traverse
the object. (listp x) is equivalent to (or (null x) (consp x)).
The empty list is a list, and a cons cell is a list.

The proper-listp function returns t only for proper lists.  A proper list is
either nil, or a cons whose cdr is a proper list. proper-listp traverses the
list, and its execution will not terminate if the list is circular.

.SS Function length-list

.TP
Syntax:

(length-list <list>)

.TP
Description:

The length-list function returns the length of <list>, which may be
a proper or improper list. The length of a list is the number of conses in that
list.

.SS Function copy-list

.TP
Syntax:

  (copy-list <list>)

.TP
Description:

The copy-list function which returns a list similar to <list>, but with
a newly allocated cons cell structure.

If <list> is an atom, it is simply returned.

Otherwise, <list> is a cons cell, and copy-list returns
(cons (car <list>) (copy-list (cdr <list>))) except that recursion
is not used.

.TP
Dialect Note:

Common Lisp does not allow the argument to be an atom, except
for the empty list nil.

.SS Function copy-cons

.TP
Syntax:

  (copy-cons <cons>)

.TP
Description:

This function creates a fresh cons cell, whose car and cdr fields are
copied from <cons>.

.SS Functions reverse, nreverse

.TP
Syntax:

  (reverse <list>)
  (nreverse <list>)

.TP
Description:

The functions reverse and nreverse produce an object which contains
the same items as proper list <list>, but in reverse order.
If <list> is nil, then both functions return nil.

The reverse function is non-destructive: it creates a new list.

The nreverse function creates the structure of the reversed list out of the
cons cells of the input list, thereby destructively altering it (if it contains
more than one element). How nreverse uses the material from the original list
is unspecified. It may rearrange the cons cells into a reverse order, or it may
keep the structure intact, but transfer the "car" values among cons cells into
reverse order.  Other approaches are possible.

.SS Function ldiff

.TP
Syntax:

  (ldiff <list> <sublist>)

.TP
Description:

The values <list> and <sublist> are proper lists.

The ldiff function determines whether <sublist> is a structural suffix of
<list> (meaning that it actually is a suffix, and is not merely equal to one).

This is true if <list> and <sublist> are the same object, or else,
recursively, if <sublist> is a suffix of (cdr <list>).

The object nil is the sublist of every list, including itself.

The ldiff function returns a new list consisting of the elements of
the prefix of <list> which come before the <sublist> suffix. The elements
are in the same order as in <list>.  If <sublist> is not a suffix of <list>,
then a copy of <list> is returned.

.TP
Examples:

  ;;; unspecified: the compiler could make '(2 3) a suffix of '(1 2 3),
  ;;; or they could be separate objects.
  (ldiff '(1 2 3) '(2 3)) -> either (1) or (1 2 3)

  ;; b is the (1 2) suffix of a, so the ldiff is (1)
  (let ((a '(1 2 3)) (b (cdr a)))
    (ldiff a b))
  -> (1)

.SS Functions flatten, flatten*

.TP
Syntax:

  (flatten <list>)
  (flatten* <list>)

.TP
Description:

The flatten function produces a list whose elements are all of the non-nil
atoms contained in the structure of <list>. The flatten* function
works like flatten except that flatten creates and returns a complete
flattened list, whereas flatten* produces a lazy list which is
instantiated on demand. This is particularly useful when the input
structure is itself lazy.

.TP
Examples:

  (flatten '(1 2 () (3 4))) -> (1 2 3 4)

  ;; precisely equivalent to previous example! nil is the same thing as ()
  (flatten '(1 2 nil (3 4))) -> (1 2 3 4)

  (flatten nil) -> nil

  (flatten '(((()) ()))) -> nil

.SS Functions memq, memql and memqual

.TP
Syntax:

  (memq <object> <list>)
  (memql <object> <list>)
  (memqual <object> <list>)

.TP
Description:

The memq, memql and memqual functions search the <list> for a member
which is, respectively, eq, eql or equal to <object>. (See the eq, eql and
equal functions below.)

If no such element found, nil is returned.

Otherwise, that tail of the list is returned whose first element
is the matching object.

.SS Functions remq, remql and remqual

.TP
Syntax:

  (remq <object> <list>)
  (remql <object> <list>)
  (remqual <object> <list>)

.TP
Description

The remq, remql and remqual functions produce a new list based on <list>,
removing the the items which are eq, eql or equal to <object>.

The input <list> is unmodified, but the returned list may share substructure
with it. If no items are removed, it is possible that the return value
is <list> itself.

.SS Functions remq*, remql* and remqual*

.TP
Syntax:

  (remq* <object> <list>)
  (remql* <object> <list>)
  (remqual* <object> <list>)

.TP
Description:

The remq*, remql* and remqual* functions are lazy versions of
remq, remql and remqual. Rather than computing the entire new list
prior to returning, these functions return a lazy list.

Caution: these functions can still get into infinite looping behavior.
For instance, in (remql* 0 (repeat '(0))), remql will keep consuming
the 0 values coming out of the infinite list, looking for the first item that
does not have to be deleted, in order to instantiate the first lazy value.

.TP
Examples:

  ;; Return a list of all the natural numbers, excluding 13,
  ;; then take the first 100 of these.
  ;; If remql is used, it will loop until memory is exhausted,
  ;; because (range 1) is an infinite list.

  [(remql* 13 (range 1)) 0..100]

.SH APPLICATIVE LIST PROCESSING

.SS Functions remove-if, keep-if, remove-if* and keep-if*

.TP
Syntax:

  (remove-if <predicate-function> <list> : <key-function>)
  (keep-if <predicate-function> <list> : <key-function>)
  (remove-if* <predicate-function> <list> : <key-function>)
  (keep-if* <predicate-function> <list> : <key-function>)

.TP
Description

The remove-if function produces a list whose contents are those of
<list> but with those elements removed which satisfy <predicate-function>.
Those elements which are not removed appear in the same order.
The result list may share substructure with the input list,
and may even be the same list object if no items are removed.

The optional <key-function> specifies how each element from the <list> is
transformed to an argument to <predicate-function>. If this argument is omitted
or specified as nil, then the predicate function is applied to the elements
directly, a behavior which is identical to <key-function> being (fun identity).

The keep-if function is exactly like remove-if, except the sense of
the predicate is inverted. The function keep-if retains those items
which remove-if will delete, and removes those that remove-if will preserve.

The remove-if* and keep-if* are like remove-if and keep-if, but
produce lazy lists.

.TP
Examples:

  ;; remove any element numerically equal to 3.
  (remove-if (op = 3) '(1 2 3 4 3.0 5)) -> (1 2 4 5)

  ;; remove those pairs whose first element begins with "abc"
  [remove-if (op equal [@1 0..3] "abc")
             '(("abcd" 4) ("defg" 5))
             car]
  -> (("defg 5))

  ;; equivalent, without test function
  (remove-if (op equal [(car @1) 0..3] "abc")
             '(("abcd" 4) ("defg" 5)))
  -> (("defg 5))

.SS Function tree-find

.TP
Syntax:

  (tree-find <obj> <tree> <test-function>)

.TP
Description:

The tree-find function searches <tree> for an occurence of <obj>.  Tree can be
any atom, or a cons. If <tree> it is a cons, it is understood to be a proper
list whose elements are also trees.

The equivalence test is performed by <test-function> which must take two
arguments, and has conventions similar to eq, eql or equal.

tree-find works as follows.  If <tree> is equivalent to <obj> under
<test-function>, then t is returned to announce a successful finding.
If this test fails, and <tree> is an atom, nil is returned immediately to
indicate that the find failed.  Otherwise, <tree> is taken to be a proper list,
and tree-find is recursively applied to each element of the list in turn, using
the same <obj> and <test-function> arguments, stopping at the first element
which returns non-nil.  

.SS Functions find and find-if

.TP
Syntax:

  (find <key> <list> [<testfun> [<keyfun>]])
  (find-if <predfun> <list> [<keyfun>])

.TP
Description:

The find and find-if functions search through a list for an item which
matches a key, or satisfies a predicate function, respectively.

The keyfun argument specifies a function which is applied to the elements
of the list to produce the comparison key. If this argument is omitted,
then the untransformed elements of the list themselves are searched.

The find function's testfun argument specifies the test function which
is used to compare the comparison keys from the list to the search key.
If this argument is omitted, then the equal function is used.
The first element from the list whose comparison key (as retrieved by
the key function) matches the search (under the test function)
is returned. If no such element is found, nil is returned.

The find-if function's predfun argument specifies a predicate function
which is applied to the successive comparison keys pulled from the list
by applying the key function to successive elements. The first element
for which the predicate function yields true is returned. If no such
element is found, nil is returned.

.SS Function set-diff

.TP
Syntax:
  (set_diff <list1> <list2> [<testfun> [<keyfun>]])

.TP
Description:

The set-diff function treats the lists <list1> and <list2> as if they were sets
and computes the set difference: a list which contains those elements in
<list1> which do not occur in <list2>.

Element equivalence is determined by a combination of testfun and keyfun.
Elements are compared pairwise, and each element of a pair is passed through
the keyfun function to produce a comparison value. The comparison values
are compared with the testfun function. If keyfun is omitted, then the
untransformed elements themselves are compared, and if testfun is omitted,
then the equal function is used.

If <list1> contains duplicate elements which do not occur in list2 (and
thus are preserved in the set difference) then these duplicates appear
in the resulting list. Furthermore, the order of the items from list1 is
preserved.

.SS Functions mapcar, mappend, mapcar* and mappend*

.TP
Syntax:

  (mapcar <function> <list> <list>*)
  (mappend <function> <list> <list>*)
  (mapcar* <function> <list> <list>*)
  (mappend* <function> <list> <list>*)

.TP
Description:

When given three arguments, the mapcar function processes applies <function> to
the elements of <list> and returns a list of the resulting values.
Essentially, the list is filtered through the function.

When additional lists are given as arguments, this filtering behavior is
generalized in the following way: mapcar traverses the lists in parallel,
taking a value from each list as an argument to the function. If there
are two lists, the function is called with two arguments and so forth.
The process is limited by the length of the shortest list.
The return values of the function are collected into a new list which is
returned.

The mappend function works like mapcar, with the following difference.
Rather than accumulating the values returned by the function into a list,
mappend expects the items returned by the function to be lists which
are catenated with append, and the resulting list is returned.
That is to say, (mappend f a b c) is equivalent to
(apply (fun append) (mapcar f a b c)). 

The mapcar* and mappend* functions work like mapcar and mappend, respectively.
However, they return lazy lists rather than generating the entire
output list prior to returning.

.TP
Caveats:

Like mappend, mappend* must "consume" empty lists. For instance,
if the function being mapped puts out a sequence of nil values,
then the result must be the empty list nil, because
(append nil nil nil nil ...) is nil.

Suppose that mappend* is used on inputs which are infinite lazy
lists, such that the function returns nil values indefinitely.
For instance:

  ;; Danger: infinite loop!!!
  (mappend* (fun identity) (repeat '(nil))) 

The mappend* function is caught in a loop trying to consume
and squash an infinite stream of nil values.

.TP
Examples:

  ;; multiply every element by two
  (mapcar (lambda (item) (* 2 item)) '(1 2 3)) -> (4 6 8)

  ;; "zipper" two lists together
  (mapcar (lambda (le ri) (list le ri)) '(1 2 3) '(a b c)) '((1 a) (2 b) (3 c)))

  ;; like append, mappend allows a lone atom or a trailing atom:
  (mappend (fun identity) 3) -> (3)
  (mappend (fun identity) '((1) 2)) -> (1 . 2)

  ;; take just the even numbers
  (mappend (lambda (item) (if (evenp x) (list x))) '(1 2 3 4 5))
  -> (2 4)

.SS Function apply

.TP
Syntax:

(apply <function> <arglist>)

.TP
Description:

The apply function converts a list of values <arglist> into individual arguments
which are passed to <function>. The return value of the apply invocation is
that of <function>.

.TP
Examples:

  ;; '(1 2 3) becomes arguments to list, thus (list 1 2 3).
  (apply (fun list) '(1 2 3)) -> (1 2 3)

.TP
Dialect note:

TXR Lisp apply does not take additional arguments before the list. 
In Common Lisp we can write (apply #'list 1 2 (list 3 4 5)) which
yields (1 2 3 4 5). In TXR Lisp, this usage can be simulated using
(apply (fun list) (list 1 2 (list 3 4 5))) or
(apply (fun list) '(,1 ,2 ,*(list 3 4 5))) .

.SS Functions reduce-left and reduce-right

.TP
Syntax:

  (reduce-left <binary-function> <list> <init-value> <key-function>)
  (reduce-right <binary-function> <list> <init-value> <key-function>)

.TP
Description:

The reduce-left and reduce-right functions reduce lists of operands
specified in <list> to a single value by the repeated application of
<binary-function>.

First, both functions initialize an internal accumulator with <init-value>.

Under reduce-left, the list is processed left to right. If elements
remain to be processed, the <binary-function> is repeatedly called with two
arguments: the accumulator and the next element from the list. After each call,
the return value of the function replaces the accumulator. When no more items
remain, the accumulator is returned.

Under reduce-right, the list is processed right to left. If elements
remain to be processed, the <binary-function> is repeatedly called with two
arguments: the next element from the list and the accumulator. After each call,
the return value of the function replaces the accumulator. When no more items
remain, the accumulator is returned.

The <key-function> specifies how each element from the <list> is converted
to an argument to <binary-function>. The value nil is equivalent to 
(fun identity), which means that each list element is taken as the value itself.


.TP
Examples:

  ;;; list is empty, so 1 is just returned:
  (reduce-left (fun +) () 1 nil)  ->  1  

  ;;; computes (- (- (- 0 1) 2) 3) 
  (reduce-left (fun -) '(1 2 3) 0 nil) -> -6

  ;;; computes (- 1 (- 2 (- 3 0)))
  (reduce-right (fun -) '(1 2 3) 0 nil) -> 2

  ;;; computes (* 1 2 3)
  (reduce-left (fun *) '((1) (2) (3)) 1 (fun first)) -> 6

.SS Function some, all and none

.TP
Syntax:

  (some <list> <predicate-fun> <key-fun>)
  (all <list> <predicate-fun> <key-fun>)
  (none <list> <predicate-fun> <key-fun>)

.TP
Description

The some, all and none functions apply a predicate test over a list of
elements.  The elements of <list> are reduced to values using <key-fun>, which
is a one-argument function. If <key-fun> is specified as nil, then (fun
identity) is substituted, and thus the values of the list are taken as they
are.

These functions have short-circuiting semantics and return conventions similar
to the and and or operators.

The some function applies <predicate-fun> to successive values
produced by retrieving elements of <list> and processing them through
<key-fun>. If the list is empty, it returns nil. Otherwise it returns the
first non-nil return value returned by a call to <predicate-fun> and
stops evaluating more elements. If <predicate-fun> returns nil for all
elements, it returns nil.

The all function applies <predicate-fun> to successive values
produced by retrieving elements of <list> and processing them through
<key-fun>. If the list is empty, it returns t. Otherwise, if
<predicate-fun> yields nil for any value,  the all function immediately
returns without invoking <predicate-fun> on any more elements.
If all the elements are processed, then the all function returns
the value which <predicate-fun> yielded for the last element.

The none function applies <predicate-fun> to successive values
produced by retrieving elements of <list> and processing them through
<key-fun>. If the list is empty, it returns t. Otherwise, if
<predicate-fun> yields  non-nil for any value, the none function
immediately returns nil. If <predicate-fun> yields nil for all
values, the none function returns t.

.TP
Examples:

  ;; some of the integers are odd
  (some (fun oddp) '(2 4 6 9) nil) -> t

  ;; none of the integers are even
  (none (fun evenp) '(1 3 4 7) nil) -> t

.SH ASSOCIATION LISTS

Association lists are ordinary lists formed according to a special convention.
Firstly, any empty list is a valid association list. A non-empty association
list contains only cons cells as the key elements. These cons cells are
understood to represent key/value associations, hence the name "association
list".

.SS Function assoc

.TP
Syntax:

  (assoc <key> <alist>)

.TP
Description:

The assoc function searches an association list <alist> for a cons cell whose
car field is equivalent to <key> (with equality determined by the equal
function). The first such cons is returned. If no such cons is found, nil is
returned.

.SS Function assq

.TP
Syntax:

  (assql <key> <alist>)

.TP
Description:

The assql function is just like assoc, except that the equality test
is determined using the eql function rather than equal.

.SS Function acons

.TP
Syntax:

  (acons <car> <cdr> <alist>)

.TP
Description:

The acons function constructs a new alist by consing a new cons to the
front of <alist>. The following equivalence holds:

  (acons car cdr alist) <--> (cons (cons car cdr) alist)

.SS Function acons-new

.TP
Syntax:

  (acons-new <car> <cdr> <alist>)

.TP
Description:

The acons-new function searches <alist>, as if using the assoc function,
for an existing cell which matches the key provided by the car argument.
If such a cell exists, then its cdr field is overwritten with the <cdr>
argument, and then the list is returned. If no such cell exists, then
a new list is returned by adding a new cell to the input list consisting
of the <car> and <cdr> values, as if by the acons function.

.SS Function aconsql-new

.TP
Syntax:

  (aconsql-new <car> <cdr> <alist>)

.TP
Description:

This function is like acons-new, except that the eql function is used
for equality testing. Thus, the list is searched for an existing cell
as if using the assql function rather than assoc.

.SS Function alist-remove

.TP
Syntax:

  (alist-remove <alist> <keys>)

.TP
Description:

The alist-remove function takes association list <alist> and produces a
duplicate from which cells matching the specified keys have been removed. The
<keys> argument is a list of the keys not to appear in the output list.

.SS Function alist-nremove

.TP
Syntax:

  (alist-nremove <alist> <keys>)

.TP
Description:

The alist-nremove function is like alist-remove, but potentially destructive.
The input list <alist> may be destroyed and its structural material re-used to
form the output list. The application should not retain references to the input
list.

.SS Function copy-alist

.TP
Syntax:

  (copy-alist <alist>)

.TP
Description:

The copy-alist function duplicates <alist>. Unlike copy-list, which
only duplicates list structure, copy-alist also duplicates each cons
cell of the input alist. That is to say, each element of the output list
is produced as if by the copy-cons function applied to the corresponding
element of the input list.

.SH PROPERTY LISTS

.SS Function prop

.TP
Syntax:

  (prop <plist> <key>)

.TP
Description:

A property list a flat list of even length consisting of interleaved
pairs of property names (usually symbols) and their values (arbitrary
objects). An example property list is (:a 1 :b "two") which contains
two properties, :a having value 1, and :b having value "two".

The prop function searches property list <plist> for key <key>. If
the key is found, then the value next to it is returned. Otherwise
nil is returned.

It is ambiguous whether nil is returned due to the property not being
found, or due to the property being present with a nil value.

.SH LIST SORTING

.SS Function merge

.TP
Syntax:

  (merge <list1> <list2> <lessfun> <keyfun>)

.TP
Description:

The merge function merges two sorted lists <list1> and <list2> into a single
sorted list. The semantics and defaulting behavior of the <lessfun> and
<keyfun> arguments are the same as those of the sort function. The input lists
are assumed to be sorted according to these functions.

This function is destructive. The application should not retain references to
the input lists, since the output list is formed out of the structure of the
input lists.

.SS Function multi-sort

.TP
Syntax:

  (multi-sort <columns> <less-funcs> [<key-funcs>])

.TP
Description:

The multi-sort function regards a list of lists to be the columns of a
database. The corresponding elements from each list constitute a record.
These records are to be sorted, producing a new list of lists.

The <columns> argument supplies the list of lists which comprise the columns of
the database. The lists should ideally be of the same length. If the lists are
of different lengths, then the shortest list is taken to be the length of the
database. Excess elements in the longer lists are ignored, and do not appear in
the sorted output.

The <less-funcs> argument supplies a list of comparison functions which are 
applied to the columns. Successive functions correspond to successive
columns. If <less-funcs> is an empty list, then the sorted database will
emerge in the original order. If <less-funcs> contains exactly one function,
then the rows of the database is sorted according to the first column. The
remaining columns simply follow their row. If <less-funcs> contains more than
one function, then additional columns are taken into consideration if the items
in the previous columns compare equal. For instance if two elements from column
one compare equal, then the corresponding second column elements are compared
using the second column comparison function.

The optional <key-funcs> argument supplies transformation functions through
which column entries are converted to comparison keys, similarly to the single
key function used in the sort function and others.  If there are more key
functions than less functions, the excess key functions are ignored.

.SH LAZY LISTS AND LAZY EVALUATION

.SS Function make-lazy-cons

.TP
Syntax:

(make-lazy-cons <function>)

.TP
Description:

The function make-lazy-cons makes a special kind of cons cell called a lazy
cons, or lcons.  Lazy conses are useful for implementing lazy lists.

Lazy lists are lists which are not allocated all at once. Rather,
their elements materialize when they are accessed, like
magic stepping stones appearing under one's feet out of thin air.

A lazy cons has "car" and "cdr" fields like a regular cons, and those
fields are initialized to nil when the lazy cons is created. A lazy cons also
has an update function, the one which is provided as the <function>
argument to make-lazy-cons.

When either the car and cdr fields of a cons are accessed for the first time,
the function is automatically invoked first. That function has the opportunity
to initialize the car and cdr fields. Once the function is called, it is removed
from the lazy cons: the lazy cons no longer has an update function.

To continue a lazy list, the function can make another call to make-lazy-cons
and install the resulting cons as the cdr of the lazy cons.

.TP
Example:

  ;;; lazy list of integers between min and max
  (defun integer-range (min max)
    (let ((counter min))
      ;; min is greater than max; just return empty list,
      ;; otherwise return a lazy list
      (if (> min max)
        nil
        (make-lazy-cons (lambda (lcons)
                          ;; install next number into car
                          (rplaca lcons counter)
                          ;; now deal wit cdr field
                          (cond
                             ;; max reached, terminate list with nil!
                            ((eql counter max) 
                             (rplacd lcons nil))
                            ;; max not reached: increment counter
                            ;; and extend with another lazy cons
                            (t
                             (inc counter)
                             (rplacd lcons (make-lazy-cons 
                                            (lcons-fun lcons))))))))))

.SS Function lcons-fun

.TP
Syntax:

(lcons-fun <lazy-cons>)

.TP
Description:

The lcons-fun function retrieves the update function of a lazy cons.
Once a lazy cons has been accessed, it no longer has an update function
and lcons-fun returns nil.  While the update function of a lazy cons is
executing, it is still accessible. This allows the update function
to retrieve a reference to itself and propagate itself into
another lazy cons (as in the example under make-lazy-cons).

.SS Function generate

.TP Syntax:
  (generate <while-fun> <gen-fun>)

.TP Description:

The generate function produces a lazy list which dynamically produces items
according to the following logic.

The arguments to generate are functions which do not take any arguments.  The
return value of generate is a lazy list. 

When the lazy list is accessed, for instance with the functions car and cdr, it
produces items on demand. Prior to producing each item, <while-fun> is
called. If it returns a true boolean value (any value other than nil), then
the <gen-fun> function is called, and its return value is incorporated as
the next item of the lazy list. But if <while-fun> yields nil, then the lazy
list immediately terminates.

Prior to returning the lazy list, generate invokes the <while-fun> one time.
If while-fun yields nil, then generate returns the empty list nil instead
of a lazy list. Otherwise, it instantiates a lazy list, and invokes
the gen-func to populate it with the first item.

.SS Function repeat

.TP
Syntax:

  (repeat <list1> {<listn>}*)

.TP
Description:

The repeat function produces an infinite lazy list formed by the repeatedly
cycled catenation of the argument lists.

.SS Operator gen

.TP
Syntax:

  (gen <while-expression> <produce-item-expression>)

.TP
Description:

The gen operator produces a lazy list, in a manner similar to the generate
function. Whereas the generate function takes functional arguments, the gen
operator takes two expressions, which is often more convenient.

The return value of gen is a lazy list. When the lazy list is accessed, for
instance with the functions car and cdr, it produces items on demand. Prior to
producing each item, the <while-expression> is evaluated, in its original
lexical scope.  If the expression yields a true value (non-nil), then
<produce-item-expression> is evaluated, and its return value is incorporated as
the next item of the lazy list. If the expression yields nil, then the lazy
list immediately terminates.

The gen operator itself immediately evaluates <while-expression> before
producing the lazy list. If the expression yields nil, then the operator
returns the empty list nil. Otherwise, it instantiates the lazy list and
invokes the <produce-item-expression> to force the first item.

.TP

Example:

  @(do
    ;; Make a lazy list of integers up to 1000
    ;; access and print the first three.
    (let* ((counter 0)
           (list (gen (< counter 1000) (inc counter))))
      (format t "~s ~s ~s\en" (pop list) (pop list) (pop list))))

  Output:
  1 2 3

.SS Operator delay

.TP
Syntax:

  (delay <expression>)

.TP
Description:

The delay operator arranges for the delayed (or "lazy") evaluation of
<expression>. This means that the expression is not evaluated immediately.
Rather, the delay expression produces a promise object.

The promise object can later be passed to the force function (described
later in this document). The force function will trigger the evaluation
of the expression and retrieve the value.

The expression is evaluated in the original scope, no mater where
the force takes place.

The expression is evaluated at most once, by the first call to force.
Additional calls to force only retrieve a cached value.

.TP
Example:

  @(do
    ;; list is popped only once: the value is computed
    ;; just once when force is called on a given promise
    ;; for the first time.

    (defun get-it (promise)
      (format t "*list* is ~s\en" *list*)
      (format t "item is ~s\en" (force promise))
      (format t "item is ~s\en" (force promise))
      (format t "*list* is ~s\en" *list*))


    (defvar *list* '(1 2 3))

    (get-it (delay (pop *list*))))

  Output:

  *list* is (1 2 3)
  item is 1
  item is 1
  *list* is (2 3)

.SS Function force

.TP
Syntax:

  (force <promise>)

.TP
Description:

The force function accepts a promise object produced by the delay function.
The first time force is invoked <promise>, the promise expression
is evaluated (in its original lexical environment, regardless of where
in the program the force call takes place). The value of the expression is
cached inside <promise> and returned, becoming the return value of the
force function call.  If the force function is invoked additional times on
the same promise, the cached value is retrieved.

.SH CHARACTERS AND STRINGS

.SS Function mkstring

.TP
Syntax:

  (mkstring <length> <char>)

.TP
Description:

The mkstring function constructs a string object of a length specified
by the <length> parameter.  Every position in the string is initialized 
with <char>, which must be a character value.

.SS Function copy-str

.TP
Syntax:

  (copy-str <string>)

.TP
Description:

The copy-str function constructs a new string whose contents are identical
to <string>.

.SS Function upcase-str

.TP
Syntax:

  (upcase-str <string>)

.TP
Description:

The upcase-str function produces a copy of <string> such that all lower-case
characters of the English alphabet are mapped to their upper case counterparts.

.SS Function downcase-str

.TP
Syntax:

  (downcase-str <string>)

.TP
Description:

The downcase-str function produces a copy of <string> such that
all upper case characters of the English alphabet are mapped to their
lower case counterparts.

.SS Function string-extend

.TP
Syntax:

  (string-extend <string> <tail>)

.TP
Description:

The string-extend function destructively increases the length of <string>,
which must be an ordinary dynamic string.  It is an error to invoke this
function on a literal string or a lazy string.

The <tail> argument can be a character, string or integer. If it is a string or
character, it specifies material which is to be added to the end of the string:
either a single character or a sequence of characters. If it is an integer, it
specifies the number of characters to be added to the string.

If <tail> is an integer, the newly added characters have indeterminate contents.
The string appears to be the original one because of an internal terminating
null character remains in place, but the characters beyond the terminating zero
are indeterminate.

.SS Function stringp

.TP
Syntax:

  (stringp <obj>)

.TP
Description:

The stringp function returns t if <obj> is one of the several
kinds of strings. Otherwise it returns nil.

.SS Function lazy-stringp

.TP
Syntax:

  (lazy-stringp <obj>)

.TP
Description:

The lazy-stringp function returns t if <obj> is a lazy
string. Otherwise it returns nil.

.SS Function length-str

.TP
Syntax:

  (length-str <string>)

.TP
Description:

The length-str function returns the length <string> in characters.
The argument must be a string.

.SS Function search-str

.TP
Syntax:

  (search-str <haystack> <needle> [<start> [<from-end>]])

.TP
Description:

The search-str function finds an occurrence of the string <needle> inside
the <haystack> string and returns its position. If no such occurrence exists,
it returns nil.

If a <start> argument is specified, it gives the starting index for the
search. If the <from-end> argument is specified and is non-nil, it means
that the search is conducted right-to-left. If multiple matches are possible,
it will find the rightmost one rather than the leftmost one.

.SS Function search-str-tree

.TP
Syntax:

  (search-str-tree <haystack> <tree> [<start> [<from-end>]])

.TP
Description:

The search-str-tree function is similar to search-str, except that instead of
searching <haystack> for the occurence of a single needle string, it searches
for the occurence of numerous strings at the same time.  These search strings
are specified, via the <tree> argument, as an arbitrarily structured tree whose
leaves are strings.

The function finds the earliest possible match, in the given search direction,
from among all of the needle strings.

If <tree> is a single string, the semantics is equivalent to
search-str.

.SS Function match-str

.TP
Syntax:

  (match-str <bigstring> <littlestring> [<start>])

.TP
Description:

The match-str function determines how many characters of <littlestring> match a
prefix of <bigstring>.

If the <start> argument is specified, then the function tests how many
characters of <littlestring> match a prefix of that portion of <bigstring>
which starts at the given position.

.SS Function match-str-tree

.TP
Syntax:

  (match-str-tree <bigstring> <tree> [<start>])

.TP
Description:

The match-str-tree function is a generalization of match-str which matches
multiple test strings against <bigstring> at the same time. The value
reported is the longest match from among any of the strings.

The strings are specified as an arbitrarily shaped tree structure which has
strings at the leaves.

If <tree> is a single string atom, then the function behaves
exactly like match-str.

.SS Function sub-str

.TP
Syntax:

  (sub-str <string> [<from> [<to>]])

.TP
Description:

The sub-str function extracts a substring from <string>. It is exactly like the
more generic function sub, except that it operates only on strings.  For a
description of the arguments and semantics, refer to the sub function.

.SS Function replace-str

.TP
Syntax:

  (replace-str <string> <item-sequence> [<from> [<to>]])

.TP
Description:

The replace-str function replaces a substring of <string> with items from
<item-sequence>, which may be any kind of sequence (list, vector
or string) provided that it, if it is nonempty, it contains only characters.

It is like the replace function, except that the first argument must be
a list.

For a description of the arguments and semantics, refer to the replace function.

.SS Function cat-str

.TP
Syntax:

  (cat-str <string-list> [<sep-string>])

.TP
Description:

The cat-str function catenates a list of strings given by <string-list> into a
single string.  The optional <sep-string> argument specifies a separator string
which is interposed between the catenated strings.

.SS Function split-str

.TP
Syntax:

  (split-str <string> <sep>)

.TP
Description:

The split-str function breaks the <string> into pieces, returing a list
thereof. The <sep> argument must be a string. It specifies the separator
character sequence within <string>. All non-overlapping occurences of
<sep> within <string> are identified in left to right order, and are removed
from <string>. The string is broken into pieces according to the gaps left
behind by the removed separators.

Adjacent occurrences of <sep> within <string> are considered to be separate
gaps which come between empty strings.

This operation is nondestructive: <string> is not modified in any way.

.SS Function split-str-set

.TP
Syntax:

  (split-str <string> <set>)

.TP
Description:

The split-str function breaks the <string> into pieces, returing a list
thereof. The <sep> argument must be a string. It specifies a set of
characters.  All occurences of any of these characters within <string> are
identified, and are removed from <string>. The string is broken into pieces
according to the gaps left behind by the removed separators.

Adjacent occurrences of characters from <set> within <string> are considered to
be separate gaps which come between empty strings.

This operation is nondestructive: <string> is not modified in any way.

.SS Function list-str

.TP
Syntax:

  (list-str <string>)

.TP
Description:

The list-str function converts a string into a list of characters.

.SS Function trim-str

.TP
Syntax:

  (trim-str <string>)

.TP
Description:

The trim-str function produces a copy of <string> from which leading and
trailing whitespace is removed. Whitespace consists of spaces, tabs,
carriage returns, linefeeds, vertical tabs and form feeds.

.SS Function string-lt

.TP
Syntax:

  (string-lt <left-str> <right-str>)

.TP
Description:

The string-lt function returns t if <left-str> is lexicographically prior
to <right-str>. The behavior does not depend on any kind of locale.

Note that this function forces (fully instantiates) any lazy string arguments,
even if doing is is not necessary.

.SS Function chrp

.TP
Syntax:

  (chrp <obj>)

.TP
Description:

Returns t if <obj> is a character, otherwise nil.

.SS Function chr-isalnum

.TP
Syntax:

  (chr-isalnum <char>)

.TP
Description:

Returns t if <char> is an alpha-numeric character, otherwise nil. Alpha-numeric
means one of the upper or lower case letters of the English alphabet found in
ASCII, or an ASCII digit. This function is not affected by locale.

.SS Function chr-isalpha

.TP
Syntax:

  (chr-isalpha <char>)

.TP
Description:

Returns t if <char> is an alphabetic character, otherwise nil. Alphabetic
means one of the upper or lower case letters of the English alphabet found in
ASCII. This function is not affected by locale.

.SS Function chr-isascii

.TP
Syntax:

  (chr-isalpha <char>)

.TP
Description:

This function returns t if the code of character <char> is in the range
0 to 127, inclusive. For characters outside of this range, it returns nil.

.SS Function chr-iscntrl

.TP
Syntax:

  (chr-iscntrl <char>)

.TP
Description:

This function returns t if the character <char> is a character whose code
ranges from 0 to 31, or is 127. In other words, any non-printable ASCII
character. For other characters, it returns nil.

.SS Function chr-isdigit

.TP
Syntax:

  (chr-isdigit <char>)

.TP
Description:

This function returns t if the character <char> is is an ASCII digit.
Otherwise, it returns nil.

.SS Function chr-isgraph

.TP
Syntax:

  (chr-isgraph <char>)

.TP
Description:

This function returns t if <char> is a non-space printable ASCII character.
It returns nil if it is a space or control character.

It also returns nil for non-ASCII characters: Unicode characters with a code
above 127.

.SS Function chr-islower

.TP
Syntax:

  (chr-islower <char>)

.TP
Description:

This function returns t if <char> is an ASCII lower case letter. Otherwise it returns nil.

.SS Function chr-isprint

.TP
Syntax:

  (chr-isprint <char>)

.TP
Description:

This function returns t if <char> is an ASCII character which is not a
control character.  It also returns nil for all non-ASCII characters: Unicode
characters with a code above 127.

.SS Function chr-ispunct

.TP
Syntax:

  (chr-ispunct <char>)

.TP
Description:

This function returns t if <char> is an ASCII character which is not a
control character.  It also returns nil for all non-ASCII characters: Unicode
characters with a code above 127.

.SS Function chr-isspace

.TP
Syntax:

  (chr-isspace <char>)

.TP
Description:

This function returns t if <char> is an ASCII whitespace character: any of the
characters in the set #\espace, #\etab, #\elinefeed, #\enewline, #\ereturn,
#\evtab, and #\epage.  For all other characters, it returns nil.

.SS Function chr-isupper

.TP
Syntax:

  (chr-isupper <char>)

.TP
Description:

This function returns t if <char> is an ASCII upper case letter. Otherwise it returns nil.

.SS Function chr-isxdigit

.TP
Syntax:

  (chr-isxdigit <char>)

.TP
Description:

This function returns t if <char> is a hexadecimal digit. One of the ASCII
letters A through F, or their lower-case equivalents, or an ASCII digit 0
through 9.

.SS Function chr-toupper

.TP
Syntax:

  (chr-toupper <char>)

.TP
Description:

If character <char> is a lower case ASCII letter character, this function
returns the upper case equivalent character. If it is some other
character, then it just returns <char>.

.SS Function chr-tolower

.TP
Syntax:

  (chr-tolower <char>)

.TP
Description:

If character <char> is an upper case ASCII letter character, this function
returns the lower case equivalent character. If it is some other
character, then it just returns <char>.

.SS Functions num-chr and chr-num

.TP
Syntax:

  (num-chr <char>)
  (chr-num <num>)

.TP
Description:

The argument <char> must be a character. The num-chr function returns that
character's Unicode code point value as an integer.

The argument <num> must be a fixnum integer in the range 0 to #\e10FFFF.
The argument is taken to be a Unicode code point value and the
corresponding character object is returned.

.SS Function chr-str

.TP
Syntax:

  (chr-str <str> <idx>)

.TP
Description:

The chr-str function performs random access on string <str> to retrieve
the character whose position is given by integer <idx>, which must
be within range of the string.

The index value 0 corresponds to the first (leftmost) character of the string
and so non-negative values up to one less than the length are possible.

Negative index values are also allowed, such that -1 corresponds to the
last (rightmost) character of the string, and so negative values down to
the additive inverse of the string length are possible.

An empty string cannot be indexed. A string of length one supports index 0 and
index -1. A string of length two is indexed left to right by the values 0 and
1, and from right to left by -1 and -2.

.TP
Notes:

Direct use of chr-str is equivalent to the DWIM bracket notation except
that <str> must be a string. The following relation holds:

  (chr-str s i) --> [s i]

since [s i] <--> (ref s i), this also holds:

  (chr-str s i) --> (ref s i)

.SS Function chr-str-set

.TP
Syntax:

  (chr-str-set <str> <idx> <char>)

.TP
Description:

The chr-str function performs random access on string <str> to overwrite
the character whose position is given by integer <idx>, which must
be within range of the string. The character at <idx> is overwritten
with character <char>.

The <idx> argument works exactly as in chr-str.

The <str> argument must be a modifiable string.

.TP
Notes:

Direct use of chr-str is equivalent to the DWIM bracket notation except
that <str> must be a string. The following relation holds:

  (chr-str-set s i c) --> (set [s i] c)

since (set [s i] c) <--> (refset s i c), this also holds:

  (chr-str s i) --> (refset s i c)

.SS Function span-str

.TP
Syntax:

  (span-str <str> <set>)

.TP
Description:

The span-str function determines the longest prefix of string <str> which
consists only of the characters in string <set>, in any combination.

.SS Function compl-span-str

.TP
Syntax:

  (compl-span-str <str> <set>)

.TP
Description:

The compl-span-str function determines the longest prefix of string <str> which
consists only of the characters which do not appear in <set>, in any
combination.

.SS Function break-str

.TP
Syntax:

  (break-str <str> <set>)

.TP
Description:

The break-str function returns an integer which represents the position of the
first character in string <str> which appears in string <set>.

If there is no such character, then nil is returned.

.SH VECTORS

.SS Function vector

.TP
Syntax:

  (vector <length>)

.TP
Description:

The vector function creates and returns a vector object of the specified
length.  The elements of the vector are initialized to nil.

.SS Function vectorp

.TP
Syntax:

  (vectorp <obj>)

.TP
Description:

The vectorp function returns t if <obj> is a vector, otherwise it returns
nil.

.SS Function vec-set-length

.TP
Syntax:

  (vec-set-length <vec> <len>)

.TP
Description:

The vec-set-length modifies the length of <vec>, making it longer or
shorter. If the vector is made longer, then the newly added elements
are initialized to nil. The <len> argument must be nonnegative.

The return value is <vec>.

.SS Function vecref

.TP
Syntax:

  (vecref <vec> <idx>)

.TP
Description:

The vecref function performs indexing into a vector. It retrieves
an element of <vec> at position <idx>, counted from zero.
The <idx> value must range from 0 to one less than the
length of the vector. The specified element is returned.

.SS Function vec-push

.TP
Syntax:

  (vec-push <vec> <elem>)

.TP
Description:

The vec-push function extends the length of a vector <vec> by one element, and
sets the new element to the value <elem>.

The previous length of the vector (which is also the position of <elem>)
is returned.

This function performs similarly to the generic function ref, except that the
first argument must be a vector.

.SS Function length-vec

.TP
Syntax:

  (length-vec <vec>)

.TP
Description:

The length-vec function returns the length of vector <vec>. It performs
similarly to the generic length function, except that the argument must
be a vector.

.SS Function size-vec

.TP
Syntax:

  (size-vec <vec>)

.TP
Description:

The size-vec function returns the number of elements for which storage
is reserved in the vector vec. 

.TP
Notes:

The length of the vector can be extended up to this size without any memory
allocation operations having to be performed.

.SS Function vector-list

.TP
Syntax:

  (vector-list <list>)

.TP
Description:

This function returns a vector which contains all of the same elements
and in the same order as list <list>.

.SS Function list-vector

.TP
Syntax:

  (list-vector <vec>)

.TP
Description:

The list-vector function returns a list of the elements of vector <vec>.

.SS Function copy-vec

.TP
Syntax:

  (copy-vec <vec>)

.TP
Description:

The copy-vec function returns a new vector object of the same length
as <vec> and containing the same elements in the same order.

.SS Function sub-vec

.TP
Syntax:

  (sub-vec <vec> [<from> [<to>]])

.TP
Description:

The sub-vec function extracts a subvector from <list>. It is exactly like the
more generic function sub, except that it operates only on vectors.
For a description of the arguments and semantics, refer to the sub function.

.SS Function replace-vec

.TP
Syntax:

  (replace-vec <vec> <item-sequence> [<from> [<to>]])

.TP
Description:

The replace-vec function replaces a subrange of <vec> with items from
the item-sequence argument, which may be any kind of sequence (list, vector
or string).

It is like the replace function, except that the first argument must be
a vector.

For a description of the arguments and semantics, refer to the replace function.

.SS Function cat-vec

.TP
Syntax:

  (cat-vec <vec-list>)

.TP
Description:

The <vec-list> argument is a list of vectors. The cat-vec function
produces a catenation of the vectors listed in <vec-list>. It returns
a single large vector formed by catenating those vectors together in
order.

.SH GENERIC SEQUENCE OPERATIONS

.SS Function length

.SS Function sub

.TP
Syntax:

   (sub <sequence> [<from> [<to>]])

Description:

The sub function extracts a slice from input sequence <sequence>. The slice is
a sequence of the same type as <sequence>.

If the <to> parameter is omitted, the behavior is as if it were specified
as nil. Likewise, if the <from> parameter is omitted, the behavior is
as if nil were specified. Thus (sub a) means (sub a nil nil).

The following equivalence holds between the sub function and
the DWIM-bracket syntax:

  (sub seq from to) <--> [seq from..to] 

The the description of the dwim operator---in particular, the
section on Range Indexing---explains the semantics of the range
specification.

If the sequence is a list, the output sequence may share
substructure with the input sequence.

.SS Function replace

.TP
Syntax:

   (replace <sequence> <replacement-sequence> [<from> [<to>]])

.TP
Description:

The replace function replaces a subsequence of the <sequence> with
<replacement-sequence>. The replaced subsequence may be empty, in which case an
insertion is performed. If <replacement-sequence> is empty (for example, the
empty list nil), then a deletion is performed.

If the <from> and <to> parameters are omitted, their values default to nil.

The following equivalence holds between assignment to a place denoted by
DWIM bracket syntax and the replace function:

  (set seq (replace seq new from to)) <--> (set [seq from..to] new)

The the description of the dwim operator---in particular, the
section on Range Indexing---explains the semantics of the range
specification.

This operation is destructive: it may work "in place" by modifying
the original sequence. The caller should retain the return value
and stop relying on the original input sequence.

.SS Functions ref and refset

.TP
Syntax:

  (ref <seq> <index>)
  (refset <seq> <index> <new-value>)

.TP
Description:

The ref and refset functions perform array-like indexing into sequences.
The ref function retrieves an element of <seq>, whereas refset overwrites an
element of <seq> with a new value.

The <index> argument is based from zero, and negative values are permitted,
with a special meaning as described in the Range Indexing section under the
description of the dwim operator.

The refset function returns the new value.

The following equivalences hold between ref and refset, and the DWIM
bracket syntax:

  (ref seq idx) <--> [seq idx]

  (refset seq idx new) <--> (set [seq idx] new)

The difference is that ref and refset are first class functions which
can be used in functional programming as higher order functions, whereas the
bracket notation is syntactic sugar, and set is an operator, not a function.
Therefore the brackets cannot replace all uses of ref and refset.

.SS Function sort

.TP
Syntax:

  (sort <sequence> <lessfun> [<keyfun>])

.TP
Description:

The sort function destructively sorts <sequence>, producing a sequence
which is sorted according to the <lessfun> and <keyfun> arguments.

The <keyfun> argument specifies a function which is applied to elements
of the sequence to obtain the key values which are then compared
using the lessfun. If <keyfun> is omitted, the identity function is used
by default: the sequence elements themselves are their own sort keys.

The <lessfun> argument specifies the comparison function which determines
the sorting order. It must be a binary function which can be invoked
on pairs of keys as produced by the key function. It must
return a non-nil value if the left argument is considered to be lesser
than the right argument. For instance, if the numeric function < is used
on numeric keys, it produces an ascending sorted order. If the function
> is used, then a descending sort is produced.

The sort function is stable for sequences which are lists. This means that the
original order of items which are considered identical is preserved.
For strings and vectors, the sort is not stable.

.SH MATH LIBRARY

.SS Arithmetic functions +, -

.TP
Syntax:

  (+ <number>*)
  (- <number> <number>*)
  (* <number>*)

.TP
Description:

The +, - and * functions perform addition, subtraction and multiplication,
respectively.  Additionally, the - function performs additive inverse.

The + function requires zero or more arguments. When called with no
arguments, it produces 0 (the identity element for adddition), otherwise it
produces the sum over all of the arguments.

Similarly, the * function requires zero or more arguments. When called
with no arguments, it produces 1 (the identity element for multiplication).
Otherwise it produces the product of all the arguments.

The semantics of - changes from subtraction to additive inverse
when there is only one argument. The argument is treated as a subtrahend,
against an implicit minuend of zero. When there are two or more
argument, the first one is the minuend, and the remaining are subtrahends.

When there are three or more operands, these operations are performed as if by
binary operations, in a left-associative way. That is to say, (+ a b c) means
(+ (+ a b) c). The sum of a b is computed first, and then this is added to c.
Similarly (- a b c) means (- (- a b) c). First, b is subtracted from a, and
then c is subtracted from that result.

The arithmetic inverse is performed as if it were subtraction from integer 0.
That is, (- x) means the same thing as (- 0 x).

The operands of +, - and * can be characters, integers (fixnum and bignum), and
floats, in nearly any combination.

If two operands have different types, then one of them is converted to the
type of the one with the higher rank, according to this ranking:
character < integer < float.  For instance if one operand is integer, and the
other float, the integer is converted to a float.

.TP
Restrictions:

Characters are not considered numbers, and participate in these operations in
limited ways. Subtraction can be used to computed the displacement between the
Unicode values of characters, and an integer displacement can be added to a
character, or subtracted from a character.  For instance (- #\e9 #\e0) is 9.  
The Unicode value of a character C can be found using (- C #\ex0): the
displacement from the NUL character.

The rules can be stated as a set of restrictions:

Two characters may not be added together.

A character may not be subtracted from an integer (which also rules out
the possibility of computing the additive inverse of a character).

A character operand may not be opposite to a floating point operand
in any operation.

A character may not be an operand of multiplication.

.SS Functions /, trunc, mod

.TP
Syntax:

  (/ <dividend> <divisor>)
  (trunc <dividend> <divisor>)
  (mod <dividend> <divisor>)

Description:

The arguments to these functions are numbers. Characters are not permitted.

The / function performs floating-point division. Each operands is first
converted to floating-point type, if necessary.

The trunc function performs a division of <dividend> by <divisor> whose result
is truncated to integer toward zero. If both operands are integers, then an
integer division is performed and the result is an integer. If either operand
is a floating point value,  a floating point division occurs, and the result is
truncated toward zero to a floating-point integral value.

The mod function performs a modulus operation. Firstly, the absolute value
of <divisor> is taken to be a modulus. Then a residue of <dividend>
with respect to <modulus> is calculated. The residue's sign follows
that of the sign of <divisor>. That is, it is the smallest magnitude
(closest to zero) residue of <dividend> with respect to the absolute
value of <divisor>, having the same sign as <divisor>.
If the operands are integer, the result is an integer. If either operand
is of type float, then the result is a float. The modulus operation is
then generalized into the floating point domain. For instance the
(mod 0.75 0.5) yields a residue of 0.25 because 0.5 "goes into" 0.75 only
once, with a "remainder" of 0.25.

.SS Function gcd

.TP
Syntax:

  (gcd <left> <right>)

.TP
Description:

The gcd function computes the greatest common divisor: the largest positive
integer which divides both arguments.

Operands <left> and <right> must be integers, or else an exception is thrown.

The value of (gcd 0 x) is 0 for all x, including 0.

The value of (gcd x 123) is is (abs x) for all x.

Negative operands are permitted; this operation effectivelly ignores sign, so
that the value of (gcd x y) is the same as (gcd (abs x) (abs y)) for all
x and y.

.SS Function abs

.TP
Syntax:

  (abs <number>)

.TP
Description:

The abs function computes the absolute value of <number>. If <number>
is positive, it is returned. If the number is negative, its additive inverse is
returned: a positive number of the same type with exactly the same magnitude.

.SS Functions floor, ceil

.TP
Syntax:

  (floor <number>)
  (ceil <number>)

.TP
Description:

The floor function returns the highest integer which does not exceed
the value of <number>. The ceiling function returns the lowest integer which
does not exceed the value of <number>.

If <number> an integer, it is simply returned.

If the argument is a float, then the value returned is a float.
For instance (floor 1.1) returns 1.0 rather than 1.

.SS Functions sin, cos, tan, asin, acos, atan

.TP
Syntax:

  (sin <radians>)
  (cos <radians>)
  (tan <radians>)
  (atan <slope>)
  (asin <num>)
  (acos <num>)

.TP
Description:

These trigonometric functions convert their argument to floating point and
return a float result. The sin, cos and tan functions compute the sine and
cosine and tangent of the <radians> argument which represents an angle
expressed in radians. The atan, acos and asin are their respective inverse
functions.  The <num> argument to asin and acos must be in the
range -1.0 to 1.0.

.SS Functions log, exp

.TP
Syntax:

  (exp <number>)
  (log <number>)

.TP
Description:

The exp function calculates the value of the transcendental number e raised to
the specified exponent.

The log function calculates the base e logarithm of its argument, which must
be a positive value.

Integer arguments are converted to floats.

.SS Functions expt, sqrt, isqrt

.TP
Syntax:

  (expt <base> <exponent>*)
  (sqrt <number>)
  (isqrt <integer>)

.TP
Description:

The expt function raises <base> to zero or more exponents given
by the <exponent> arguments.
(expt x) is equivalent to (expt x 1); and yields x for all x.
For three or more arguments, the operation is left associative.
That is to say, (expt x y z) is equivalent to (expt (expt x y) z) and
so forth. Exponentiation is done pairwise using a binary operation.
If both operands to this binary operation are integers, then the
result is an integer. If either operand is a float, then the other
operand is converted to a float, and a floating point exponentation
is performed. Exponentation that would produce a complex number is
not supported.

The sqrt function produces a floating-point square root. The numeric
oeprand is converted from integer to floating-point if necessary.
Negative operands are not supported.

The isqrt function computes an integer square root: a value which is the
greatest integer that is no greater than the true square root of the input
value. The input value must be an integer.

.SS Function exptmod

.TP
Syntax:

  (exptmod <base> <exponent> <modulus>)

.TP
Description:

The exptmod function performs modular exponentiation and accepts only integer
arguments. Furthermore, <exponent> must be a non-negative and <modulus>
must be positive.

The return value is <base> raised to <exponent>, and reduced to the
least positive residue modulo <modulus>.

.SS Functions fixnump, bignump, integerp, floatp, numberp

.TP
Syntax:

  (fixnump <object>)
  (bignump <object>)
  (integerp <object>)
  (floatp <object>)
  (numberp <object>)

.TP
Description:

These functions test the type of <object>, returning true if it is an object
of the implied type. The fixnump, bignump and floatp functions return true if
the object is of the basic type fixnum, bignum or float.
The function integerp returns true of <object> is either a fixnum or
a bignum. The function numberp returns true if the object is either
a fixnum, bignum or float.

.SS Function zerop

.TP
Syntax:

  (zerop <number>)

.TP
Description:

The zerop function tests <number> for equivalence to zero. The argument must be
a number. It returns t for the integer value 0,  and for the floating-point
value 0.0. For other numbers, it returns nil.

.SS Functions evenp, oddp

.TP
Syntax:

  (evenp <integer>)
  (oddp <integer>)

.TP
Description:

The evenp and oddp functions require integer arguments. evenp returns
t if <integer> is even (divisible by two), otherwise it returns nil.
oddp returns t if <integer> is not divisible by two (odd), otherwise
it returns nil.

.SS Functions >, <, >=, <= and =

.TP
Syntax:

  (> <number> <number>*)
  (< <number> <number>*)
  (>= <number> <number>*)
  (<= <number> <number>*)
  (= <number> <number>*)

.TP
Description:

These relational functions compare characters and numbers for numeric equality
or inequality. The arguments must be one or more numbers or characters.

If just one argument is given, then these functions all return t.

If two arguments are given, then, they are compared as follows.
First, if the numbers do not have the same type, then the one
which has the lower ranking type is converted to the type of
the other, according to this ranking: character < integer < float.
For instance if a character and integer is compared, the character
is converted to integer. Then a straightforward numeric comparison
is applied.

Three or more arguments may be given, in which case the comparison proceeds
pairwise from left to right. For instance in (< a b c), the comparison (< a b)
is performed in isolation. If it yields false, then nil is returned, otherwise
the comparison (< b c) is performed in isolation, and if that yields false, nil
is returned, otherwise t is returned.  Note that it is possible for b to
undergo two different conversions.  For instance in (< <float> <character>
<integer>), the character will convert to a floating-point representation of
its Unicode, and if that comparison suceeds, then in the second comparison, the
character will convert to integer.

.SS Function /=

.TP
Syntax:

  (/= <number>*)

.TP
Description:

The arguments to /= may be numbers or characters.  The /= function returns t if
no two of its arguments are numerically equal. That is to say, if there exist
some a and b which are distinct arguments such that (= a b) is true, then
teh function returns nil. Otherwise it returns t.

.SS Functions max and min

.TP
Syntax:

  (max <number> <number>*)
  (min <number> <number>*)

.TP
Description:

The max and min functions determine and return the highest or lowest
value from among their arguments.

The arguments must be numbers or characters.

If only a single argument is given, that value is returned.

If two arguments are given, then (max a b) is equivalent to (if (>= a b) a b),
and (min a b) is equivalent to (if (<= a b) a b). If the operands do not
have the same type, then one of them is converted to the type of the other;
however, the original unconverted values are returned. For instance
(max 4 3.0) yields the integer 4, not 4.0.

If three or more arguments are given, max and min are left-associative.
Thus (max a b c) is (max (max a b) c).

.SS Functions int-str, flo-str and num-str

.TP
Syntax:

  (int-str <string> <radix>)
  (flo-str <string>)
  (num-str <string>)

.TP
Description:

These functions extract numbers <string>. Leading whitespace, if
any, is skipped. If no digits can be successfully extracted, then nil is
returned.  Trailing material which does not contribute to the number
is ignored.

The int-str function converts a string of digits in the specified
radix to an integer value. For radices above 10, letters of the alphabet
are used for digits: A represent a digit whose value is 10, B represents 11 and
so forth until Z.  For values of radix above 36, the returned value is
unspecified. Upper and lower case letters are recognized.
Any character which is not a digit of the specified radix is regarded
as the start of trailing junk at which the extraction of the digits stops.

The flo-str function converts a floating-point decimal notation to a nearby
floating point value. The material which contributes to the value
is the longest match for optional leading space, followed by a
mantissa which consists of an optional sign followed by a mixture of at least
one digit, and at most one decimal point, optionally followed by an exponent
part denoted by the letter E or e, an optional sign and one or more optional
exponent digits.

The num-str function converts a decimal notation to either an integer as if by
a radix 10 application of int-str, or to a floating point value as if by
flo-str. The floating point interpretation is chosen if the possibly empty
initial sequence of digits (following any whitespace and optional sign) is
followed by a period, e or E.

.SS Functions int-flo and flo-int

.TP
Syntax:

  (int-flo <float>)
  (flo-int <integer>)

.TP
Description:

These functions perform numeric conversion between integer and floating point
type. The int-flo function returns an integer by truncating toward zero.
The flo-int function returns an exact floating point value corresponding to the
integer argument, if possible, otherwise an approximation using a nearby
floating point value.

.SH EXCEPTIONS

.SS Functions throw, throwf and error

.SS Operator catch

.TP
Syntax:

  (catch <try-expression>
    {(<symbol> (<arg>*) <body-form>*)}*)

.TP
Description:

The catch operator establishes an exception catching block around
the <try-expression>. The <try-expression> is followed by zero or more
catch clauses. Each catch clause consists of a symbol which denotes
an exception type, an argument list, and zero or more body forms.

If <try-expression> terminates normally, then the catch clauses
are ignored. The catch itself terminates, and its return value is
that of the <try-expression>.

If <try-expression> throws an exception which is a subtype of one or more of
the type symbols given in the exception clauses, then the first (leftmost) such
clause becomes the exit point where the exception is handled.
The exception is converted into arguments for the clause, and the clause
body is executed. When the clause body terminates, the catch terminates,
and the return value of the catch is that of the clause body.

If <try-expression> throws an exception which is not a subtype of any of
the symbols given in the clauses, then the search for an exit point for
the exception continues through the enclosing forms. The catch clauses
are not involved in the handling of that exception.

When a clause catches an exception, the number of arguments in the catch must
match the number of elements in the exception.  A catch argument list
resembles a function or lambda argument list, and may be dotted.  For instance
the clause (foo (a . b)) catches an exception subtyped from foo, with one or
more elements. The first element binds to parameter a, and the rest, if any,
bind to parameter b.  If there is only one element, b takes on the value nil.

Also see: the unwind-protect operator, and the functions throw, throwf
and error.

.SH REGULAR EXPRESSION LIBRARY

.SS Functions search-regex and match-regex

.TP
Syntax:

 (search-regex <haystack-string> <needle-regex> : <start> <from-end>)
 (match-regex <string> <regex> : <position>)

.TP
Description

These functions perform regular-expression-based searching and matching.

The search-regex function searches through <haystack-string> starting
at position <start> for a match for <needle-regex>. If <start> is omitted,
the search starts at position 0. If <from-end> is specified, the search
proceeds in reverse, from the last position in the string, toward <start>.
This function returns nil if no match is found, otherwise it returns
a cons pair, whose car indicates the position of the match, and whose
cdr indicates the length of the match. 

The match-regex function tests whether <regex> matches at <position>
in <string>. If <position> is not specified, it is taken to be zero.
If the regex matches, then the length of the match is returned.
If it does not match, then nil is returned.
.
.SS Function regsub

.TP
Syntax:

  (regsub <regex> <replacement> <string>)

.TP
Description:

The regsub function searches <string> for multiple occurences of
non-overlapping matches for <regex>.  A new string is constructed
similar to <string> but in which each matching region is replaced
with using <replacement> as follows.

The <replacement> object may be a character or a string, in which 
case it is simply taken to be the replacement for each match
of the regular expression.

The <replacement> object may be a function of one argument, in
which case for every match which is found, this function is invoked,
with the matching piece of text as an argument. The function's
return value is then taken to be the replacement text.

.TP
Examples:

  ;; match every lower case e or o, and replace by filtering
  ;; through the upcase-str function:
  
  [regsub #/[eo]/ upcase-str "Hello world!"] -> "HEllO wOrld!"

  ;; Replace Hello with Goodbye:
  (regsub #/Hello/ "Goodbye" "Hello world!") -> "Goodbye world!"

.SS Function regexp

.TP
Syntax:

  (regexp <obj>)

.TP
Description:

The regexp function returns t if <obj> is a compiled regular expression
object. For any other object type, it returns nil.

.SS Function regex-compile

.TP
Syntax:

  (regex-compile <form>)

.TP
Description:

The regex compile function takes the source code of a regular expression,
expressed as a Lisp data structure, and compiles it to a regular expression
object.

.TP
Examples:

  ;; the equivalent of #/[a-zA-Z0-9_/
  (regex-compile '(set (#\ea . #\ez) (#\eA . #\eZ) (#\e0 . #\e9) #\e_))

  ;; the equivalent of #/.*/ and #/.+/
  (regex-compile '(0+ wild))
  (regex-compile '(1+ wild))

  ;; #/a|b|c/
  (regex-compile '(or (or #\ea #\eb) #\ec))

.SH HASHING LIBRARY

.SS Functions make-hash, hash

.TP
Syntax:

  (make-hash <weak-keys> <weak-vals> <equal-based>)
  (hash [ :weak-keys ] [ :weak-vals ] [ :equal-based ])

.TP
Description:

These functions construct a new hash table, using different syntax.

A hash table is an object which retains an association between pairs of
objects. Each pair consists of a key and value. Given an object which is
similar to a key in the hash table, it is possible to retrieve the
corresponding value. Entries in a hash table are not ordered in any way, and
lookup is facilitated by hashing: quickly mapping a key object to a numeric
value which is then used to index into one of many buckets where the matching
key will be found (if such a key is present in the hash table).

make-hash takes three mandatory boolean arguments. The <weak-keys>
argument specifies, whether the hash table shall have weak keys. The <weak-vals>
argument specifies whether it shall have weak values, and
<equal-based> specifies whether it is equal-based.  The hash function defaults
all three of these properties to false, and allows them to be overridden to
true by the presence of keyword arguments.

The hash function provides an alternative interface. It accepts optional
arguments which are keyword symbols. Any combination of the three symbols
:weak-keys, :weak-vals and :equal-based can be specified in any order
to turn on the corresponding properties in the newly constructed hash table.
If any of the keywords is not specified, the corresponding property defaults to
nil. 

If a hash table has weak keys, this means that from the point of view
of garbage collection, that table holds only weak references to the keys
stored in it.  Similarly, if a hash table has weak values, it means that it
holds a weak reference to each value stored. A weak reference is one
which does not prevent the reclamation of an object by the garbage
collector. That is to say, when the garbage collector discovers that the only
references to some object are weak references, then that object is considered
garbage, just as if it had no references to it. The object is reclaimed, and
the weak references "lapse" in some way, which depends on what kind they are.
Hash table weak references lapse by entry removal: if either a key or a value
object is reclaimed, then the corresponding key-value entry is erased from the
hash table.

Important to the operation of a hash table is the criterion by which keys are
considered same. By default, this similarity follows the eql function.  A hash
table will search for a stored key which is eql to the given search key.
A hash table constructed with the equal-based property compares keys using
the equal function instead.

In addition to storing key-value pairs, a hash table can have a piece of
information associated with it, called the user data.

.SS Functions make-similar-hash and copy-hash

.TP
Syntax:

  (make-similar-hash <hash>)
  (copy-hash <hash>)

.TP
Description:

The make-similar-hash and copy-hash functions create a new hash object based on
the existing <hash> object.

The make-similar-hash produces an empty hash table which inherits all of the
attributes of <hash>. It uses the same kind of key equality, the
same configuration of weak keys and values, and has the same user data (see
the set-hash-userdata function).

The copy-hash function is like make-similar-hash, except that instead of
producing an empty hash table, it produces one which has all the same elements
as <hash>: it contains the same key and value objects. 

.SS Function sethash

.TP
Syntax:

  (sethash <hash> <key> <value>)

.TP
Description:

The sethash function places a value into <hash> table under the given <key>.
If a similar key already exists in the hash table, then that key's
value is replaced by <value>. Otherwise, the <key> and <value> pair is
newly inserted into <hash>.

.SS Function pushhash

.TP
Syntax:

  (pushhash <hash> <key> <element>)

.TP
Description:

The pushhash function is useful when the values stored in a hash table
are lists.  If the given <key> does not already exist in <hash>, then a list of
length one is made which contains <element>, and stored in <hash> table under
<key>.  If the <key> already exists in the hash table, then the corresponding
value must be a list. The <element> value is added to the front of that list,
and the extended list then becomes the new value under <key>.

.SS Function remhash

.TP
Syntax:

  (remhash <hash> <key>)

.TP
Description:

The remhash function searches <hash> for a key similar to the
<key>. If that key is found, then that key and its corresponding value are
removed from the hash table.

.SS Function hash-count

.TP
Syntax:

  (hash-count <hash>)

.TP
Description:

The hash-count function returns an integer representing the number of
key-value pairs stored in <hash>.

.SS Function get-hash-userdata

.TP
Syntax:

  (get-hash-userdata <hash>)

.TP
Description:

This function retrieves the user data object associated with <hash>.
The user data object of a newly created hash table is initialized to nil.

.SS Function set-hash-userdata

.TP
Syntax:

  (set-hash-userdata <hash> <object>)

.TP
Description:

The set-hash-userdata replaces, with the <object>, the user data object
associated with <hash>.

.SS Function hashp

.TP
Syntax:

  (hashp <object>)

.TP
Description:

The hashp function returns t if the <object> is a hash table,
otherwise it returns nil.

.SS Function maphash

.TP
Syntax:

  (maphash <hash> <binary-function>)

.TP
Description:

The maphash function successively invokes binary-function for each key-value
pair present in <hash>. The key and value are passed as arguments
to <binary-function>.

.SS Functions hash-eql and hash-equal

.TP
Syntax:

  (hash-eql <object>)
  (hash-equal <object>)

.TP
Description:

These functions each compute an integer hash value from the internal
representation of <object>, which satisifes the following properties.
If two objects A and B are the same under the eql function, then
(hash-eql A) and (hash-eql B) produce the same integer hash value.  Similarly,
if two objects A and B are the same under the equal function, then (hash-equal
A) and (hash-equal B) each produce the same integer hash value.  In all other
circumstances, the hash values of two distinct objects are unrelated, and
may or may not be equal.

.SS Functions hash_keys, hash_values, hash_pairs, and hash_alist

.TP
Syntax:
  (hash-keys <hash>)
  (hash-values <hash>)
  (hash-pairs <hash>)
  (hash-alist <hash>)

.TP
Description:

These functions retrieve the bulk key-value data of hash table <hash>
in various ways. hash-keys retrieves a list of the keys. hash-values
retrieves a list of the values. hash-pairs retrieves a list of pairs,
which are two-element lists consisting of the key, followed by the value.
Finally, hash-pairs retrieves the key-value pairs as a Lisp association list:
a list of cons cells whose car fields are keys, and whose cdr fields
are the values. 

These functions all retrieve the keys and values in the
same order. For example, if the keys are retrieved with hash-keys,
and the values with hash-values, then the corresponding entries from
each list correspond to the pairs in the hash table.

.SS Operator dohash

.TP
Syntax:

  (dohash (<key-var> <value-var> <hash-form> [<result-form>])
    <body-form>*)

.TP
Description:

The dohash operator iterates over a hash table. The <hash-form> expression must
evaluate to an object of hash table type. The <key-var> and <value-var>
arguents must be symbols suitable for use as variable names.
Bindings are established for these variables over the scope of the
<body-form>-s and the optional result form.

For each element in the hash table, the <key-var> and <value-var>
variables are set to the key and value of that entry, respectively,
and each <body-form>, if there are any, is evaluated.

When all of the entries of the table are thus processed, the <result-form> is
evaluated, and its return value becomes the return value of the dohash form. If
there is no <result-form>, the return value is nil.

The <result-form> and <body-form>-s are in the scope of an implicit anonymous
block, which means that it is possible to terminate the execution of
dohash early using (return) or (return <value>).

.SS Functions hash-uni, hash-diff and hash-isec

.TP
Syntax:

  (hash-uni <hash1> <hash2>)
  (hash-diff <hash1> <hash2>)
  (hash-isec <hash1> <hash2>)

.TP
Description:

These functions perform basic set operations on hash tables in a nondestructive
way, returning a new hash table without altering the inputs. The arguments
<hash1> and <hash2> must be compatible hash tables.  This means that their keys
must use the same kind of equality.

The resulting hash table inherits attributes from <hash1>, as if by the
make-similar-hash operation. If <hash1> has userdata, the resulting hash table
has the same userdata. If <hash1> has weak keys, the resulting table has weak
keys, and so forth.

The hash-uni function performs a set union. The resulting hash contains all of the
keys from <hash1> and all of the keys from <hash2>, and their corresponding values.
If a key occurs both in <hash1> and <hash2>, then it occurs only once in the
resulting hash. The value for this common key is the one from <hash2>.

The hash-diff function performs a set difference. First, a copy of <hash1> is
made as if by the copy-has function. Then from this copy, all keys which occur
in <hash2> are deleted.

The hash-isec function performs a set intersection. The resulting hash contains
only those keys which occur both in <hash1> and <hash2>. The values selected
for these common keys are those from <hash1>.

.SH PARTIAL EVALUATION AND COMBINATORS

.SS Operator op

.TP
Syntax:

  (op {<form>}+)

.TP
Description:

Like the lambda operator, the op operator creates an anonymous function.
The difference is that the arguments of the function are implicit, or
optionally specified within the function body.

Also, the <form> arguments of op are implicitly turned into a DWIM expression,
which means that argument evaluation follows Lisp-1 rules.  (See the dwim
operator below).

The argument forms are arbitrary expressions, within which a special
convention is permitted:

.IP @<num>

A number preceded by a @ is a metanumber. This is a special syntax
which denotes an argument. For instance @2 means that the second argument of
the anonymous function is to be substituted in place of the @2. If @2 is used
it means that @1 also has to appear somewhere, otherwise the op
construct is erroneous.

.IP @rest

The meta-symbol @rest indicates that any trailing arguments to the
function are to be inserted. If the @<num> syntax is not used anywhere,
it means that the function only has trailing arguments. If @1 is used,
it means that the second and subsequent arguments are trailing arguments.
If @rest is not used anywhere, then the rest arguments are automatically
applied to the op form. If @rest appears, then this is suppressed.

The actions of form may be understood by these examples, which show
how op is rewritten to lambda.  However, note that the real translator
uses generated symbols for the arguments, which are not equal to any
symbols in the program.

  (op) -> invalid

  (op +) -> (lambda rest [+ . rest])

  (op @1 @2) -> (lambda (arg1 arg2 . rest) [arg1 arg2 . rest])

  (op foo @1 (@2) (bar @3)) -> (lambda (arg1 arg2 arg3 . rest) 
                                  [foo arg1 (arg2) (bar arg3) . rest])

  (op foo @rest @1) -> (lambda (arg1 . rest) [foo rest arg1])

.TP

Examples:

  ;; Take a list of pairs and produce a list in which those pairs
  ;; are reversed.

  (mapcar (op list @2 @1) '((1 2) (a b)))   ->   ((2 1) (b a))

.SS Function chain

.TP
Syntax:

   (chain {<func>}*)

.TP
Description:

The chain function accepts zero or more functions as arguments, and returns
a single function, called the chained function, which represents the chained
application of those functions, in left to right order.

If chain is given no arguments, then it returns a variadic function which
ignores all of its arguments and returns nil.

Otherwise, the first function may accept any number of arguments. The second
and subsequent functions, if any, must accept one argument.

The chained function can be called with an argument list which is acceptable
to the first function. Those arguments are in fact passed to the first
function. The return value of that call is then passed to the second
function, and the return value of that call is passed to the third function
and so on. The final return value is returned to the caller.

.TP
Example:

  (call [chain + (op * 2)] 3 4) -> 14

In this example, a two-element chain is formed from the + function
and the function produced by (op * 2) which is a one-argument
function that returns the value of its argument multiplied by two.
(See the definition of the op operator).

The chained function is invoked using the call function, with the arguments 3
and 4. The chained evaluation begins by passing 3 and 4 to the + function,
which yields 7.  This 7 is then passed to the (op * 2) doubling function,
resulting in 14.

A way to write the above example without the use of the DWIM brackets and the
op operator is this:

  (call (chain (fun +) (lambda (x) (* 2 x))) 3 4)

.SS Functions andf and orf

.TP
Syntax:

  (andf {<func>}*)
  (orf {<func>}*)

.TP
Description:

The andf and orf functions are the functional equivalent of the and and or
operators. These functions accept multiple functions and return a new function
which represents the logical combination of those functions.

The input functions should have the same arity. Or, rather, there should exist
some common argument arity with which they can all be invoked. The resulting
combined function is then callable with that many arguments.

The andf operator returns a function which combines the input functions with
short-circuiting logical conjunction. The resulting function passes its
arguments to the functions successively, in left to right order. As soon as any
of the functions returns nil, then nil is returned immediately, and the
remaining functions are not called.  Otherwise, if none of the functions return
nil, then the value returned by the last function is returned. If the list of
functions is empty, then t is returned.  That is, (andf) returns a function
which accepts any arguments, and returns t.

The orf operator combines the input functions with a short-circuiting logical
disjunction. The function produced by orf passes its arguments down to the
functions successively, in left to right order.  As soon as any function
returns a non-nil value, that value is returned and the remaining functions are
not called. If all functions return nil, then nil is returned. The expression
(orf) returns a function which accepts any arguments and returns nil.


.SS Function iff

.TP
Syntax:

  (iff <cond-func> <then-func> [<else-func>])

.TP
Description:

The iff function is the functional equivalent of the if operator. It accepts
functional arguments and returns a function.

The resulting function takes its arguments and applies them to <cond-func>.  If
<cond-func> yields true, then the arguments are passed to <then-func,> and the
resulting value is returned. Otherwise if <cond-func> yields a false result,
and there is no <else-func,> then nil is returned. If <cond-func> yields false,
and an <else-func> exists, then the original arguments are passed to
<else-func> and the resulting value is returned.

.SH INPUT AND OUTPUT

TXR Lisp supports input and output streams of various kinds, with
generic operations that work across the stream types.

In general, I/O errors are usually turned into exceptions. When the description
of error reporting is omitted from the description of a function, it can be
assumed that it throws an error.

.SS Variables *stdout*, *stddebug*, *stdin* and *stderr*

These variables hold predefined stream objects. The *stdin*, *stdout* and
*stderr* streams closely correspond to the underlying operating system streams.
Various I/O functions require stream objects as arguments.

The *stddebug* stream goes to the same destination as *stdout*, but is
a separate object which can be redirected independently, allowing debugging
output to be separated from normal output.

.SS Function format

.TP
Syntax:

  (format <stream-designator> <format-string> {<args>}*)

.TP
Description:

The format function performs output to a stream given by <stream-designator>,
by interpreting the actions implicit in a <format-string>, incorporating
material pulled from additional arguments given by <args>. Though the function
is simple to invoke, there is complexity in format string language, which is
documented below.

The <stream-designator> argument can be a stream object, or one of the values t
and nil. The value t serves as a shorthand for *stdout*. The value nil
means that the function will send output into a newly instantiated string
output stream, and then return the resulting string.

.TP
Format string syntax:

Within <format-string>, most characters represent themselves. Those
characters are simply output. The character ~ (tilde) introduces formatting
directives, which are denoted by a letter. 

The special sequence ~~ (tilde-tilde) codes a single tilde. Nothing is
permitted between the two tildes.

The syntax of a directive is generally as follows:

  ~[<width>[,<precision>]]<letter>

The <letter> is a single alphabetic character which determines the
general action of the directive. The optional width and precision
can be numeric digits, or special codes documented below. 

The width specifier gives the width of the character field in which the object's
printed representation is placed. If the printed representation overflows the
field width, then the field width is ignored. The default field width is zero.
If the width specifier begins with the < (left angle bracket) character, then
the printing will be left-adjusted within this field. Otherwise it will be
right-adjusted by default.  The width can be specified as decimal digits, or as
the character *. The * notation means that instead of digits, the value of the
next argument is consumed, and expected to be an integer which specifies the
width. If that integer value is negative, then the field will be left-adjusted.
(If that value is positive, but the < notation is present prior to the *
notation, the field will also be left-adjusted).

The meaning of the precision specifier depends on the format directive.
Also, when the precision is not specified, the default behavior may be
different from any specific precision value.
If the precision has a leading zero, this has special semantics for numeric
conversions. The precision may also have a leading sign character, which
may be a plus or space. 

.TP
Format directives:

Format directives are case sensitive, so that for example ~x and ~X have a
different effect, and ~A doesn't exist wheras ~a does. They are:

.IP a
Prints any object in an aesthetic way, as if by the pprint function.
The aesthetic notation violates read-print consistency: this notation
is not necessarily readable if it is implanted in TXR source code.
The field width specifier is honored, including the left-right adjustment
semantics. The precision field has a meaning as follows. For integer objects,
the precision specifies the minimum number of digits to print. (A leading
sign does not count as a digit).  If the precision field has a leading zero,
then the number is padded with zeros to the required number of digits,
otherwise the number is padded with spaces instead of zeros.  If zero or space
padding is present, and a leading positive or negative sign must be printed,
then it is placed before leading zeros, or after leading spaces, as the case
may be. If the precision specifier has a leading + sign, then a + sign is
printed for positive numbers. If the precision specifier has a leading space
instead of a + sign, then the + sign is rendered as a space for positive
numbers. If there is no leading space or +, then a sign character is omitted
for positive numbers.  For floating point values, the precision specifies
the maximum number of total significant figures, which do not include any
digits in the exponent, if one is printed. Numbers are printed in exponential
notation if their magnitude is small, or else if their exponent exceeds
their precision. (If the precision is not specified, then it defaults to
the system-dependent number of digits in a floating point value, derived
from the C language DBL_DIG constant.) Floating point values which are
integers are printed without a trailing .0 (point zero). For all other objects,
the precision specifies the maximum number of characters to print. 
The object's printed representation is crudely truncated at that number
of characters.

.IP s
Prints any object in a standard way, as if by the print function.  Objects for
which read-print consistency is possible are printed in a way such that
if their notation is implanted in TXR source, they are readable.
The field width specifier is honored, including the left-right adjustment
semantics. The precision field is treated very similarly to the ~a
format directive, except that non-exponentiated floating point numbers that
would be mistaken for integers include a trailing ".0" for the sake read-print
consistency. Objects truncated by precision may not have read-print
consistency. For instance, if a string object is truncated, it loses its
trailing closing quote, so that the resulting representation is no longer
a properly formed string object.

.IP x
Requires an argument of character or integer type. The integer value or
character code is printed in hexadecimal, using lower-case letters
for the digits "a" through "f". Width and precision semantics
are as described for the "a" format directive, for integers.

.IP X
Like the "x" directive, but the digits "a" through "f" are rendered
in upper case.

.IP o
Like the "x" directive, but octal is used instead of hexadecimal.

.IP f
The "f" directive prints numbers in a fixed point decimal notation, with
a fixed number of digits after the decimal point. It requires a numeric
argument. (Unlike "x", "X" and "o", characters are not permitted).
The precision specifier gives the number of digits past the decimal point.
The number is rounded off to the specified precision, if necessary.
Furthermore, that many digits are always printed, regardless of the actual
precision of the number or its type.  If it is omitted, then the default value
is three: three digits past the decimal point. A precision of zero means no
digits pas the decimal point, and in this case the decimal point is suppressed
(regardless of whether the numeric argument is floating-point or integer).  

.IP e
The "e" directive prints numbers in exponential notation. It requires
a numeric argument. (Unlike "x", "X" and "o", characters are not permitted).
The precision specifier gives the number of digits past the decimal point
printed in the exponential notation, not counting the digits in the exponent.
Exactly that many digits are printed, regardless of the precision of the
number.  If the precision is omitted, then the number of digits after the
decimal point is three. If the precision is zero, then a decimal portion is
truncated off entirely, including the decimal point.

.SS Functions print, pprint, tostring, tostringp

.TP
Syntax:

  (print <obj> [<stream>])
  (pprint <obj> [<stream>])
  (tostring <obj>)
  (tostringp <obj>)

.TP
Description:

The print and pprint functions render a printed character representation of the
<obj> argument into <stream>. If a stream argument is not supplied, then 
the destination is the stream currently stored in the *stdout*
variable. The print function renders in a way which strives for read-print
consistency: an object is printed in a notation which is recognized as
a similar object of the same kind when it appears in TXR source code.
The pprint function ("pretty print") does not strive for read-print consistency.
For instance it prints a string object simply by dumping its characters, rather
than by adding the surrounding quotes and rendering escape syntax for
special characters.

The tostring and tostringp functions are like print and pprint, but
they do not accept a stream argument, instead printing to a freshly
instantiated string stream, and returning the resulting string.

The following equivalences hold between calls to the format function
and calls to these functions:

  (format stream "~s" obj)  <-->  (print obj stream)
  (format t "~s" obj)       <-->  (print obj)
  (format nil "~s" obj)     <-->  (tostring obj)

For pprint and tostringp, the equivalence is produced by using "~a"
in format rather than "~s".

.SS Function make-string-input-stream

.TP
Syntax:

  (make-string-input-stream <string>)

.TP
Description:

This function produces an input stream object. Character read operations on the
stream object read successive characters from <string>. Output
operations and byte operations are not supported.

.SS Function make-string-byte-input-stream

.TP
Syntax:

  (make-string-byte-input-stream <string>)

.TP
Description:

This function produces an input stream object. Byte read operations on
this stream object read successive byte values obtained by encoding
<string> into UTF-8. Character read operations are not supported, and neither
are output operations.

.SS Function make-string-output-stream

.TP
Syntax:

  (make-string-output-stream)

.TP
Description:

This function, which takes no arguments, creates a string output stream.
Data sent to this stream is accumulated into a string object.
String output streams supports both character and byte output operations. 
Bytes are assumed to represent a UTF-8 encoding, and are decoded in order
to form characters which are stored into the string. 

If an incomplete UTF-8 code is output, and a character output operation then
takes place, that code is assumed to be terminated and is decoded as invalid
bytes.  The UTF-8 decoding machine is reset and ready for the start of a new
code.

The get-string-from-stream function is used to retrieve the accumulated
string.

If the null character is written to a string output stream, either via
a character output operation or as a byte operation, the resulting string
will appear to be prematurely terminated. TXR strings cannot contain null
bytes.

.SS Function get-string-from-stream

.TP
Syntax:

  (get-string-from-stream <stream>)

.TP
Description:

The <stream> argument must be a string output stream. This function finalizes
the data sent to the stream and retrieves the accumulated character string.

If a partial UTF-8 code has been written to <stream>, and then this
function is called, the byte stream is considered complete and the partial
code is decoded as invalid bytes.

After this function is called, further output on the stream is not possible.

.SS Function make-strlist-output-stream

.TP
Syntax:

  (make-strlist-output-stream)

.TP
Description:

This function is closely analogous to make-string-output-stream. However,
instead of producing a string, it produces a list of strings. The
data is broken into multiple strings by newline characters written
to the stream. Newline characters do not appear in the string list. Also, byte
output operations are not supported.

.SS Function get-list-from-stream

.TP
Syntax:

  (get-list-from-stream <stream>)

.TP
Description:

This function returns the string list which has accumulated inside
a string output stream given by <stream>. The string output stream is
finalized, so that further output is no longer possible.

.SS Function close-stream

.TP
Syntax:

  (close-stream <stream>)

.TP
Description:

The close-stream function performs a close operation on <stream>,
whose meaning is depends on the type of the stream. For some types of streams,
such as string streams, it does nothing. For streams which are connected
to operating system files or devices, will perform a close of the underlying
file descriptor, and dissociate that descriptor from the stream. Any buffered
data is flushed first.

.SS Functions get-line, get-char and get-byte

.TP
Syntax:

  (get-line [<stream>])
  (get-char [<stream>])
  (get-byte [<stream>])

.TP
Description:

These fundamental stream functions perform input.  The <stream> argument
is optional. If it is specified, it should be an input stream which supports
the given operation. If it is not specified, then the *stdin* 
stream is used.

The get-char function pulls a character from a stream which supports character
input.  Streams which support character input also support the get-line
function which extracts a line of text delimited by the end of the stream or a
newline character and returns it as a string. (The newline character does not
appear in the string which is returned). 

Character input from streams based on bytes requires UTF-8 decoding, so that
get-char actually may read several bytes from the underlying low level
operating system stream.

The get-byte function bypasses UTF-8 decoding and reads raw bytes from
any stream which supports byte input. Bytes are represented as integer
values in the range 0 to 255.

Note that if a stream supports both byte input and character input, then mixing
the two operations will interfere with the UTF-8 decoding.

.SS Functions put-string, put-line, put-char and put-byte

.TP
Syntax:

  (put-line <string> [<stream>])
  (put-string <string> [<stream>])
  (put-char <char> [<stream>])
  (put-byte <byte> [<stream>])

.TP
Description:

These functions perform output on an output stream. The <stream> argument
must be an output stream which supports the given operation. If it is omitted,
then *stdout* is used.

The put-char function writes a character given by <char> to a stream. If the
stream is based on bytes, then the character is encoded into UTF-8 and multiple
bytes are written. Streams which support put-char also support put-line, and
put-string. The put-string function writes the characters of a string out to
the stream as if by multiple calls to put-char. The put-line function is like
put-string, but also writes an additional newline character.

The put-byte function writes a raw byte given by the <byte> argument
to <stream>, if <stream> supports a byte write operation. The byte
value is specified as an integer value in the range 0 to 255.

.SS Function flush-stream

.TP
Syntax:

  (flush-stream <stream>)

.TP
Description:

This function is meaningful for output streams which accumulate data
which is passed on to the operating system in larger transfer units.
Calling this function causes all accumulated data inside <stream> to be passed
to the operating system. If called on streams for which this function is not
meaningful, it does nothing.

.SH FILESYSTEM ACCESS

.SS Function stat

.SS Function open-directory

.SS Functions open-file

.SH COPROCESSES

.SS Functions open-command, open-process

.SH SYMBOLS AND PACKAGES

.SS Variables *user-package*, *keyword-package*, *system-package*

.SS Function make-sym

.SS Function make-package

.SS Function find-package

.SS Function intern

.SS Function symbolp

.SS Function symbol-name

.SS Function symbol-package

.SS Function keywordp

.SH PSEUDO-RANDOM NUMBERS

.SS Variable *random-state*

.SS Function make-random-state

.SS Function random-state-p

.SS Functions random-fixnum and random

.SS Functions range and range*

.SH TIME

.SS Functions time and time-usec

.SH WEB PROGRAMMING SUPPORT

.SS Functions url-encode and url-decode

.SH ACCESS TO TXR PATTERN LANGUAGE FROM LISP

.SS Function match-fun

.SH DEBUGGING FUNCTIONS

.SS Functions source-loc and source-loc-str

.SH MODULARIZATION

.SS Variable *self-path*

.SH DEBUGGER

.B TXR
has a simple, crude, built-in debugger. The debugger is invoked by adding
the the -d command line option to an invocation of txr.
In this debugger it is possible to step through code, set breakpoints,
and examine the variable binding environment.

Prior to executing any code, the debugger waits at the txr> prompt,
allowing for the opportunity to set breakpoints.

Help can be obtained with the h or ? command.

Whenever the program stosp at the debugger, it prints the Lisp-ified
piece of syntax tree that is about to be interpreted.
It also shows the context of the input being matched.

The s command can be used to step into a form; n to step over.
Sometimes the behavior seems counter-intuitive. For instance stepping
over a @(next) directive actually means skipping everything which follows
it. This is because the query material after a @(next) is actually child
nodes in the abstract syntax tree node of the next directive.

.SS Sample Session

Here is an example of the debugger beign applied to a web scraping program
which connects to a US NAVY clock server to retrieve a dynamically-generated
web page, from which the current time is extracted, in various time zones.
The handling of the web request is done by the wget command; the txr
query opens a wget command as and scans the body of the HTTP response containing
HTML. This is the code, saved in a file called navytime.txr:

  @(next `!wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null`)
  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN>
  <html>
  <body>
  <TITLE>What time is it?</TITLE>
  <H2> US Naval Observatory Master Clock Time</H2> <H3><PRE>
  @(collect :vars (MO DD HH MM SS (PM "  ") TZ TZNAME))
  <BR>@MO. @DD, @HH:@MM:@SS @(maybe)@{PM /PM/} @(end)@TZ@/\t+/@TZNAME
  @  (until)
  </PRE>@/.*/
  @(end)
  </PRE></H3><P><A HREF="http://www.usno.navy.mil"> US Naval Observatory</A>

  </body></html>
  @(output)
  @  (repeat)
  @MO-@DD @HH:@MM:@SS @PM @TZ
  @  (end)
  @(end)

This is the debug session:

  $ txr -d navytime.txr
  stopped at line 1 of navytime.txr
  form: (next (sys:quasi "!wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null"))
  depth: 1
  data (nil):
  nil

The user types s to step into the (next ...) form.

  txr> s
  stopped at line 2 of navytime.txr
  form: (sys:text "<!DOCTYPE" (#<sys:regex: 95e4590> 1+ #\space) "HTML" (#<sys:regex: 95e4618> 1+ #\space) "PUBLIC" (#<sys:regex: 95e46a8> 1+ #\space) "\"-//W3C//DTD" (#<sys:regex: 95e4750> 1+ #\space) "HTML" (#<sys:regex: 95e47d8> 1+ #\space) "3.2" (#<sys:regex: 95e4860> 1+ #\space) "Final\"//EN>")
  depth: 2
  data (1):
  "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final\"//EN>"
  txr> s

The current form now is a syt:text form which is an internal representation of
a block of horizontal material. The pattern matching is in vertical mode at
this point, and so the line of data is printed without an indication of
character position. 

  stopped at line 2 of navytime.txr
  form: (sys:text "<!DOCTYPE" (#<sys:regex: 95e4590> 1+ #\space) "HTML" (#<sys:regex: 95e4618> 1+ #\space) "PUBLIC" (#<sys:regex: 95e46a8> 1+ #\space) "\"-//W3C//DTD" (#<sys:regex: 95e4750> 1+ #\space) "HTML" (#<sys:regex: 95e47d8> 1+ #\space) "3.2" (#<sys:regex: 95e4860> 1+ #\space) "Final\"//EN>")
  depth: 3
  data (1:0):
  "" . "<!DOCTYPE HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"

The user types s to step in.

  txr> s
  stopped at line 2 of navytime.txr
  form: "<!DOCTYPE"
  depth: 4
  data (1:0):
  "" . "<!DOCTYPE HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"

Now, the form about to be processed is the first item of the (sys:text ...),
a the string "<!DOCTYPE". 

The input is shown broken into two quoted strings with a dot in between.
The dot indicates the current position. The left string is emtpy, meaning
that this is the leftmost position. The programmer steps:

  txr> s
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e4590> 1+ #\espace)
  depth: 4
  data (1:9):
  "<!DOCTYPE" . " HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"

Control has now passed to the second element of the (sys:text ...),
a regular expression which matches one or more spaces, generated by
a single space in the source code according to the language rules.

The input context shows taht "<!DOCTYPE" was matched in the input, and the
position moved past it.

  txr> s
  stopped at line 2 of navytime.txr
  form: "HTML"
  depth: 4
  data (1:10):
  "<!DOCTYPE " . "HTML PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"

Now, the regular expression has matched and moved the psoition past
the space; the facing input is now "HTML ...".

The programmer then repeats the s command by hitting Enter.

  txr> 
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e4618> 1+ #\espace)
  depth: 4
  data (1:14):
  "<!DOCTYPE HTML" . " PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: "PUBLIC"
  depth: 4
  data (1:15):
  "<!DOCTYPE HTML " . "PUBLIC \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e46a8> 1+ #\espace)
  depth: 4
  data (1:21):
  "<!DOCTYPE HTML PUBLIC" . " \e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: "\e"-//W3C//DTD"
  depth: 4
  data (1:22):
  "<!DOCTYPE HTML PUBLIC " . "\e"-//W3C//DTD HTML 3.2 Final\e"//EN>"
  txr>
  stopped at line 2 of navytime.txr
  form: (#<sys:regex: 95e4750> 1+ #\espace)
  depth: 4
  data (1:34):
  "<!DOCTYPE HTML PUBLIC \e"-//W3C//DTD" . " HTML 3.2 Final\e"//EN>"

It is not evident from the session transcript, but during interactive use,
the input context appears to be animated. Whenever the programmer hits
Enter, the new context is printed and the dot appears to advance.

Eventually the programmer becomes bored and place a breakpoint on line 15,
where the @(output) block begins, and invokes the c command to continue the
execution:

  txr> b 15
  txr> c
  stopped at line 15 of navytime.txr
  form: (output (((repeat nil (((sys:var MO nil nil) "-" (sys:var DD nil nil) " " (sys:var HH nil nil) ":" (sys:var MM nil nil) ":" (sys:var SS nil nil) " " (sys:var PM nil nil) " " (sys:var TZ nil nil))) nil nil nil nil nil nil))))
  depth: 2
  data (16):
  ""

The programmer issues a v command to take a look at the variable bindings,
which indicate that the @(collect) has produced some lists.

  txr> v
  bindings:
  0: ((PM "  " "PM" "PM" "PM" "PM" "PM" "PM") (TZNAME "Universal Time" "Eastern Time" "Central Time" "Mountain Time" "Pacific Time" "Alaska Time" "Hawaii-Aleutian Time") (TZ "UTC" "EDT" "CDT" "MDT" "PDT" "AKDT" "HAST") (SS "35" "35" "35" "35" "35" "35" "35") (MM "32" "32" "32" "32" "32" "32" "32") (HH "23" "07" "06" "05" "04" "03" "01") (DD "30" "30" "30" "30" "30" "30" "30") (MO "Mar" "Mar" "Mar" "Mar" "Mar" "Mar" "Mar"))

Then a continue command, which finishes the program, whose output appears:

  txr> c
  Mar-30 23:22:52    UTC
  Mar-30 07:22:52 PM EDT
  Mar-30 06:22:52 PM CDT
  Mar-30 05:22:52 PM MDT
  Mar-30 04:22:52 PM PDT
  Mar-30 03:22:52 PM AKDT
  Mar-30 01:22:52 PM HAST

.SH APPENDIX A: NOTES ON EXOTIC REGULAR EXPRESSIONS

Users familiar with regular expressions may not be familiar with the complement
and intersection operators, which are often absent from text processing tools
that support regular expressions.  The following remarks are offered in hope
that they are of some use.

.SS Equivalence to Sets

Regexp intersection is not essential; it may be obtained from complement and
union as follows, since De Morgan's law applies to regular expression algebra:
(R1)&(R2) = ~(~(R1)|~(R2)). (The complement of the union of the complements of
R1 and R2 constitutes the intersection.) This law works because the regular
expression operators denote set operations in a straightforward way. A regular
expression denotes a set of strings (a potentially infinite one) in a condensed
way. The union of two regular expressions R1 | R2 denotes the union of the set
of texts denoted by R1 and that denoted by R2. Similarly R1 & R2 denotes a set
intersection, and ~R denotes a set complement. Thus algebraic laws
that apply to set operations apply to regular expressions. It's useful to keep
in mind this relationship between regular expressions and sets in understanding
intersection and complement.

Given a finite set of strings, like the set { "abc", "def" }, which corresponds
to the regular expression (abc|def), the complement is the set which contains
an infinite number of strings: it consists of all possible strings except "abc"
and "def". It includes the empty string, all strings of length 1, all strings
of length 2, all strings of length 3 other than "abc" and "def", all strings of
length 4, etc.  This means that a "harmless looking" expression like ~(abc|def)
can actually match arbitrarily long inputs.

.SS Set Difference

How about matching only three-character-long strings other than "abc" or "def"?
To express this, regex intersection can be used: these strings are the
intersection of the set of all three-character strings, and the set of all
strings which are not "abc" or "def". The straightforward set-based reasoning
leads us to this: ...&~(abc|def).   This A&~B idiom is also called set
difference, sometimes notated with a minus sign: A-B (which is not
supported in 
.B TXR
regular expression syntax).  Elements which are in the set A, but not B, are
those elements which are in the intersection of A with the complement of B.
This is similar to the arithmetic rule A - B = A + -B: subtraction is
equivalent to addition of the additive inverse. Set difference is a useful
tool: it enables us to write a positive match which captures a more general set
than what is intended (but one whose regular expression is far simpler
than a positive match for the exact set we want), then we can
intersect this over-generalized set with the complemented set of
another regular expression which matches the particulars that we wish excluded.

.SS Expressivity versus Power

It turns out that regular expressions which do not make use of the
complement or intersection operators are just as powerful as expressions
that do. That is to say, with or without these operators, regular expressions
can match the same sets of strings (all regular languages).  This means that
for a given regular expression which uses intersection and complement, it is
possible to find a regular expression which doesn't use these operators, yet
matches the same set of strings.  But, though they exist, such equivalent
regular expressions are often much more complicated, which makes them difficult
to design.  Such expressions do not necessarily
. B express
what it is they match; they merely capture the equivalent set. They
perform a job, without making it obvious what it is they do.  The use of
complement and intersection leads to natural ways of expressing many kinds of
matching sets, which not only demonstrate the power to carry out an operation,
but also easily express the concept.

.SS Example: Matching C Language Comments

For instance, using complement, we can write a straightforward regular
expression which matches C language comments. A C language
comment is the digraph /*, followed by any string which does not contain the
closing sequence */, followed by that closing sequence.
Examples of valid comments are /**/, /* abc */ or /***/. But C
comments do not nest (cannot contain comments), so that 
/* /* nested */ */ actually consists of the comment /* /* nested */,
which is followed by the trailing junk */.
Our simple characterization of interior part of a C comment as a string
which does not contain the terminating digraph makes use of the
complement, and can be expressed using the complemented regular expression like
this: (~.*[*][/].*).  That is to say, strings which contain */ are matched by
the expression .*[*][/].*: zero or more arbitrary characters, followed by
*/, followed by zero or more arbitrary characters. Therefore, the complement of this expression matches all other strings: those which do not contain */.
These strings up the inside of a C comment between the /* and */.

The equivalent simple regex is quite a bit more complicated.
Without complement, we must somehow write a positive match for all strings such
that we avoid matching */. Obviously, sequences of characters other than *
are included: [^*]*.   Occurrences of * are also allowed, but only if followed
by something other than a slash, so let's include this via union:

  ([^*]|[*][^/])*. 

Alas, already, we have a bug in this expression. The
subexpression [*][^/] can match "**", since a * is not a /.  If the next
character in the input is /, we missed a comment close.  To fix the problem we
revise to this: 

  ([^*]|[*][^*/])*

(The interior of a C language comment is a any
mixture of zero or more non-asterisks, or digraphs consisting of an asterisk
followed by something other than a slash or another asterisk).  Oops, now we
have a problem again. What if two asterisks occur in a comment?  They are not
matched by [^*], and they are not matched by [*][^*/]. Actually, our regex must
not simply match asterisk-non-asterisk digraphs, but rather sequences of one or
more asterisks followed by a non-asterisk: 

  ([^*]|[*]*[^*/])*

This is still not right, because, for instance, it fails to match the interior
of a comment which is terminated by asterisks, including the simple test cases
where the comment interior is nothing but asterisks.  We have no provision in
our expression for this case; the expression requires all runs of asterisks to
be followed by something which is not a slash or asterisk. The way to fix this
is to add on a subexpression which optionally matches a run of zero or more
interior asterisks before the comment close: 

  ([^*]|[*]*[^*/])*[*]*

Thus our the semi-final regular expression is

  [/][*]([^*]|[*]*[^*/])*[*]*[*][/]

(A C comment is an interior string enclosed in /* */, where this interior part
consists of a mixture of non-asterisk characters, as well as runs of asterisk
characters which are terminated by a character other than a slash, except for
possibly one rightmost run of asterisks which extends to the end of the
interior, touching the comment close. Phew!) One final simplification is
possible: the tail part [*]*[*][/]  can be reduced to [*]+[/] such that the
final run of asterisks is regarded as part of an extended comment terminator
which consists of one or more asterisks followed by a slash.   The regular
expression works, but it's cryptic; to someone who has not developed it, it
isn't obvious what it is intended to match.  Working out complemented matching
without complement support from the language is not impossible, but it may be
difficult and error-prone, possibly requiring multiple iterations of
trial-and-error development involving numerous test cases, resulting in an
expression that doesn't have a straightforward relationship to the original
idea.

.SS The Non-Greedy Operator

The non-greedy operator % is actually defined in terms of a set difference,
which is in turn based on intersection and complement. The uninteresting case
(R%) where the right operand is empty reduces to (R*): if there is no trailing
context, the non-greedy operator matches R as far as possible, possibly to the
end of the input, exactly like the greedy Kleene.  The interesting case (R%T)
is defined as a "syntactic sugar" for the equivalent expression
((R*)&(~.*(T&.+).*))T   which means: match the longest string which is matched
by R*, but which does not contain a non-empty match for T; then, match T.  This
is a useful and expressive notation. With it, we can write the regular
expression for matching C language comments simply like this: [/][*].%[*][/]
(match the opening sequence /*, then match a sequence of zero or more
characters non-greedily, and then the closing sequence */.  With the non-greedy
operator, we don't have to think about the interior of the comment as set of
strings which excludes */.  Though the non-greedy operator appears expressive,
its apparent simplicity may be deceptive.  It looks as if it works "magically"
by itself; "somehow" this .% "knows" only to consume enough characters so that
it doesn't swallow an occurrence of the trailing context. Care must be taken
that the trailing context passed to the operator really is the correct text
that should be excluded by the non-greedy match. For instance, take the
expression .%abc.  If you intend the trailing context to be merely a, you must
be careful to write (.%a)bc. Otherwise the trailing context is abc, and this
means that the .% match will consume the longest string that does not contain
"abc", when in fact what was intended was to consume the longest string that
does not contain a. The change in behavior of the % operator upon modifying the
trailing context is not as intuitive as that of the * operator, because the
trailing context is deeply involved in its logic.  For single-character
trailing contexts, it may be a good idea to use a complemented character class
instead. That is to say, rather than (.%a)bc, consider [^a]*bc. The set of
strings which don't contain the character a is adequately expressed by [^a]*.

.SH APPENDIX B: NOTES ON FALSE

The reason for printing the word
.IR false
on standard output when
a query doesn't match, in addition to returning a failed termination
status, is that the output of
.B TXR
may be collected by a shell script, by the application of eval to command
substitution syntax. Printing
.IR false
will cause eval to evaluate the
.IR false
command, and thus failed status will propagate from the eval
itself.   The eval command conceals the termination status of a
program run via command substitution.  That is to say, if a program
fails, without producing output, its output is substituted into the eval
command which then succeeds, masking the failure of the program. For example:

  eval "$(false)"

appears successful: the false utility indicates a failed status, but
produces no output. Eval evaluates an empty script and reports success;
the failed status of the false program is forgotten.
Note the difference between the above and this:

  eval "$(echo false)"

This command has a failed status. The echo prints the word false and succeeds;
this false word is then evaluated as a script, and thus interpreted as the
false command which fails. This failure
.B is
propagated as the result of the eval
command.