File: lang.texi

package info (click to toggle)
librep 0.17-13
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 5,648 kB
  • ctags: 2,969
  • sloc: ansic: 32,770; lisp: 12,399; sh: 7,971; makefile: 515; sed: 93
file content (9336 lines) | stat: -rw-r--r-- 301,847 bytes parent folder | download | duplicates (4)
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
@c The Programmer's Manual -*-Texinfo-*-

@chapter The language
@cindex The language
@cindex Lisp, the rep dialect
@cindex rep, the Lisp dialect

This chapter of the manual is a full guide to the librep Lisp
programming language, including documentation for most of the built-in
functions.

@menu
* Intro::                       Introduction and Lisp conventions

Fundamental data types.

* Data Types::                  Data types and values in Lisp
* Numbers::                     Numeric representations and functions
* Sequences::                   Ordered sequences of data values
* Symbols::                     Symbols are uniquely named objects

The core language.

* Evaluation::                  Evaluating expressions
* Variables::                   Symbols represent named variables
* Functions::                   The building blocks of Lisp programs
* Macros::                      User-defined control structures
* Definitions::                 Block-structured definitions
* Modules::                     Scoping for "global" definitions
* Control Structures::          Conditionals, loops, etc@dots{}
* Threads::                     Multi-threaded programs
* Loading::                     Programs are stored in files
* Compiled Lisp::               Making programs run faster

Data structures and I/O.

* Datums::                      Low-level data type definition
* Queues::                      FIFO queue type
* Records::                     Defining structured data types
* Hash Tables::                 Efficient table lookups
* Guardians::                   Protecting objects from GC
* Streams::                     Data sinks and sources; character streams
* Hooks::                       Hooks promote extensibility
* Files::                       Manipulating files in the filing system
* Processes::                   launch and control subprocesses when
                                 running under Unix

Miscellaneous features.

* Regular Expressions::         Matching regular expressions
* Time and Date::               Manipulating time and date
* i18n::                        Internationalisation

* System Information::          Getting details about the host
* User Information::            The name of the user
* Environment Variables::       Reading and writing the environment
* String Functions::            Misc string manipulation
* Sleeping::                    Waiting for a period of time
* Beeping::                     Making a ding! sound
* Messages::                    Writing to the console
* Command Line Options::        Retrieving command line arguments
* Shell Commands::              Executing shell commands
* Timers::                      Asynchronous timers

* Debugging::                   How to debug Lisp programs
* Tips::                        General ideas for @code{librep} programming
@end menu

This manual still fails to document the following functions: 
default-boundp,
default-value,
recursive-edit,
regexp-cache-control,
sdbm-close,
sdbm-delete,
sdbm-error,
sdbm-fetch,
sdbm-firstkey,
sdbm-nextkey,
sdbm-open,
sdbm-rdonly,
sdbm-store,
sdbmp,
set-default,
setq-default,


@node Intro, Data Types, , The language
@section Introduction
@cindex Introduction, Lisp

As you have probably gathered by now, @code{librep} provides a dialect
of the Lisp programming language---a dialect originally inspired by
Emacs Lisp, but later adapted to include many features from various
Scheme implementations and Common Lisp. The language dialect aims to be
convenient for both extending applications and writing large
stand-alone programs.

All programs written using only the information in this manual should
be compatible with future revisions of @code{librep}.

This following sections explain some of the most important Lisp concepts
and the conventions I've used in this manual.

@menu
* nil and t::                   Boolean values in Lisp
* The Lisp Reader::             Basic program structure
* Notation::                    Special glyphs used
* Descriptions::                How functions and variables are documented
@end menu


@node nil and t, The Lisp Reader, , Intro
@subsection nil and t
@cindex nil and t
@cindex t
@cindex Boolean values

In the rep Lisp dialect there is a single data value representing
boolean ``false''---the empty list, written as @code{()}. All other
values are considered ``not-false'', i.e. ``true''.

By convention the constants @code{nil} and @code{t} are used to
represent the canonical boolean values. The constant variable
@code{nil} evaluates to the empty list (i.e. ``false''), while @code{t}
evaluates to itself (i.e. not-``false'', therefore ``true'').

Reiterating, all of the conditional operations regard @emph{anything}
which is not @code{()} as being true (i.e. non-false). The actual
symbol @code{t} should be used where a true boolean value is explicitly
stated, to increase the clarity of the code.

So, @code{()}, and its alias @code{nil}, represent both the empty list
and boolean falsehood. Most Lisp programmers write @code{()} where its
value as a list should be emphasized, and @code{nil} where its value as
boolean false is intended. Although neither of these values need be
quoted (@pxref{Quoting}), most programmers will quote the empty list to
emphasize that it is a constant value. However @code{nil} should not be
quoted, doing so would produce the @emph{symbol} @code{nil}, not
boolean falsehood. For example:

@lisp
(append '() '()) @result{} ()          ;Emphasize use of empty lists

(not nil) @result{} t                  ;Emphasize use as boolean false

(get 'nil 'color)               ;Use the symbol @code{nil}
@end lisp

When a function is said to ``return false'', it means that it returns
the false boolean value, i.e. the empty list. When a function is said
to ``return true'', this means that any non-false value is returned.


@node The Lisp Reader, Notation, nil and t, Intro
@subsection The Lisp Reader
@cindex The Lisp reader
@cindex Reader, the Lisp

Lisp programs and functions are stored internally as Lisp data objects,
the Lisp Reader is the mechanism that translates from textual
descriptions of Lisp objects to the internal data structures
representing them.

@findex read
The Lisp Reader is the collection of internal functions accessed by the
@code{read} Lisp function. It reads a character at a time from an input
stream until a whole Lisp object has been parsed.

@xref{Data Types}.


@node Notation, Descriptions, The Lisp Reader, Intro
@subsection Notation
@cindex Notation
@cindex Manual notation

Wherever an example of evaluating a Lisp form is shown it will be
formatted like this,

@lisp
(+ 1 2)
    @result{} 3
@end lisp

@noindent
The glyph @samp{@result{}} is used to show the computed value of a
form. @footnote{In this case the list @samp{(+ 1 2)} (i.e. the list
containing three elements, the symbol @code{+} and, the numbers 1 and
2), represents a function application. The first element in the list is
the name of the function to be called, all other elements are the
arguments to apply to it. Since the @code{+} function adds a series of
numbers, the above function call is actually performing the computation
@samp{1 + 2}.}

When two forms are shown as being exactly equivalent to one another the
glyph @samp{@equiv{}} is used, for example,

@lisp
(car some-variable) @equiv{} (nth 0 some-variable)
@end lisp

Evaluating some forms result in an error being signalled, this is denoted
by the @samp{@error{}} glyph.

@lisp
(open-file "/tmp/foo" 'read)
    @error{} File error: No such file or directory, /tmp/foo
@end lisp


@node Descriptions, , Notation, Intro
@subsection Descriptions
@cindex Descriptions
@cindex Functions, descriptions of
@cindex Variables, descriptions of

In this document the simplest type of descriptions are those defining
variables (@pxref{Variables}), they look something like:

@defvar grains-of-sand
This imaginary variable contains the number of grains of sand in a
one-mile long stretch of an averagely sandy beach.
@end defvar

Hooks (@pxref{Hooks}) are also described in this format, the only
difference is that @samp{Variable:} is replaced by @samp{Hook:}.

Functions (@pxref{Functions}) and macros (@pxref{Macros}) have more
complex descriptions; as well as the name of the object being
described, they also have a list of parameters which the object will
accept. Each parameter in the list is named and may be referred to in
the body of the description.

Three keyword parameters may also be used: @code{#!optional},
@code{#!key} and @code{#!rest}. They have the same meaning as when used
in the lambda-list of a function definition (@pxref{Lambda
Expressions}). That is, @code{#!optional} means that all further
parameters are optional, and @code{#!rest} means that the following
parameter actually receives a list of any unused argument values.

An example function definition follows.

@defun useless-function first @code{#!optional} second @code{#!rest} tail
This function returns a list consisting of the values @var{second} (when
undefined the number 42 is used), all the items in the list @var{tail}
and @var{first}.

@lisp
(useless-function 'foo 'bar 'xyz 20)
    @result{} (bar xyz 20 foo)

(useless-function '50)
    @result{} (42 50)
@end lisp
@end defun

Macros and interactive commands are defined in the same way with
@samp{Macro:} or @samp{Command:} replacing @samp{Function:}.

Special forms (@pxref{Special Forms}) are described similarly to
functions except that the argument list is formatted differently, since
special forms are, by definition, more flexible in how they treat their
arguments. Optional values are enclosed in square brackets
(@samp{[@var{optional-arg}]}) and three dots
(@samp{@var{repeated-arg}@dots{}}) indicate where zero or more
arguments are allowed.


@node Data Types, Numbers, Intro, The language
@section Data Types
@cindex Data types

The way that data is represented in Lisp is fundamentally different to
languages such as C or Fortran. In Lisp each piece of data (or
@dfn{value}) has two basic attributes: the data and the @emph{type} of
the data. This means that type checking is performed at run-time on the
actual data itself, not at compile-time on the ``variable'' holding the
data.

Also, there are no ``pointers'' in Lisp. As in the Java programming
language, all values are references to data structures, with each
actual data structure (or @dfn{Lisp Object}) being able to have as many
values referring to it concurrently as necessary. Because of this lack
of pointers, there can be no memory-leakage in Lisp---when an object
has no more extant references, it is automatically deallocated
(@pxref{Garbage Collection}).

Most Lisp objects are a member of one of the primitive types; these are
types built into the Lisp system and can represent things like strings,
numbers, cons cells, vectors, etc@dots{} Other primitive types may be
defined at run-time.

More complex objects may be constructed from these primitive types, for
example a vector of three elements could be regarded as a type
@code{triple} if necessary. In general, each separate type provides a
predicate function which returns true when applied to an object of
its own type.

Finally, one of the most important differences between Lisp and other
languages is that there is no distinction between programs and data.
But this will be explained later.

@menu
* Types Summary::               List of the most common types
* Read Syntax::                 Some types can be made from source code
* Printed Representation::      All types can be printed
* Equality Predicates::         How to test two objects for equality
* Comparison Predicates::       Comparing two objects as scalars
* Type Predicates::             Each type has a predicate defining it
* Garbage Collection::          Reusing memory from stale objects
@end menu


@node Types Summary, Read Syntax, , Data Types
@subsection Types Summary
@cindex Types summary
@cindex Data types, summary of

Each separate data type is documented in its own section, this is a just a
summary of the more common types.

@table @dfn
@item Numbers
Numbers: fixnums, bignums, rationals and floats. @xref{Numbers}.

@item Cons cell
An object referring to two other Lisp objects. @xref{Cons Cells}.

@item List
A sequence of objects, in Lisp lists are not primitive types, instead they
are made by chaining together Cons cells. @xref{Lists}.

@item Vector
A one-dimensional array of objects. @xref{Vectors}.

@item String
A vector of characters. @xref{Strings}.

@item Array
An ordered sequence of objects which can be accessed in constant time,
either a vector or a string. @xref{Sequences}.

@item Sequence
An ordered sequence of objects, either a list or an array.
@xref{Sequences}.

@item Symbol
A symbol is a named object; they are used to provide named variables and
functions. @xref{Symbols}.

@item File
A link to a notional file in the filing system. This file may be in the
local filing system, or on a FTP server, or wherever. @xref{Files}. 

@item Process
An object through which processes may be created and controlled.
@xref{Processes}.

@item Stream
Serial data sinks and sources. These may include files, functions, and
processes. @xref{Streams}.

@item Void
The empty type, only used in symbols to represent an undefined value.
Note that this is not the same as @code{()}, which is the empty list,
or false truth value.
@end table


@node Read Syntax, Printed Representation, Types Summary, Data Types
@subsection Read Syntax
@cindex Read syntax
@cindex Syntax of objects

As previously noted the Lisp reader translates textual descriptions of
Lisp objects into the object they describe (source files are simply
descriptions of objects). However, not all data types can be created
in this way: in fact the only types which can are numbers, strings,
symbols, cons cells (or lists) and vectors, all others have to be
created by calling functions.

@cindex Comments
Single line comments are introduced by a semi-colon character
(@samp{;}). Whenever the Lisp reader encounters a semi-colon where it's
looking for the read syntax of a new Lisp object it will discard the
rest of the line of input. Block comments are also supported,
introduced by the string @samp{#|} and terminated by @samp{|#}.
@xref{Comment Styles}.

The @dfn{read syntax} of an object is the string which when given to the
reader as input will produce the object. The read syntax of each type
of object is documented in that type's main section of this manual but
here is a small summary of how to write each type.

@table @asis
@item Numbers
A number is number written as an integer---decimal, octal (when the
number is preceded by @samp{#o}) or hexadecimal (when the number is
preceded by @samp{#x})---or a decimal rational or floating point value.
An optional minus sign may be the first character in a number. Some
examples are,

@lisp
42
    @result{} 42

#o177
    @result{} 127

#x-ff
    @result{} -255

3/2
    @result{} 3/2

1.23
    @result{} 1.23
@end lisp

@item Strings
The read syntax of a string is simply the string with a double-quote
character (@samp{"}) at each end, for more details see @ref{Strings}.

@lisp
"This is a string"
@end lisp

@item Cons cells
A cons cell is written in what is known as @dfn{dotted pair notation},
an opening left-parenthesis, followed by the read syntax of the first
object, followed by a dot, then the second object, and finally a
closing right-parenthesis. For example:

@lisp
("car" . "cdr")
@end lisp

@item Lists
The syntax of a list is similar to a cons cell, but the dot is removed
and zero or more objects may be written:

@lisp
(0 1 2 3)

("foo" ("bar" "baz") 100)
@end lisp

@noindent
The second example is a list of three elements, a string, an inner list
and a number.

@item Vectors
The read syntax of a vector is similar to that of a list, but with
square brackets instead of parentheses,

@lisp
[0 1 2 3]
@end lisp

@item Symbols
The read syntax of a symbol is its name, for example the read syntax of
the symbol called @samp{my-symbol} is,

@lisp
my-symbol
@end lisp
@end table


@node Printed Representation, Equality Predicates, Read Syntax, Data Types
@subsection Printed Representation
@cindex Printed representation

As well as translating textual descriptions to Lisp objects, the
process may be reversed, converting a value back to a textual
description. The resulting text is known as the @dfn{printed
representation} of the object, and will usually be very similar to the
read syntax of the object (@pxref{Read Syntax}).

Objects which do not have a read syntax @emph{do} have a printed
representation, it will normally be of the form,

@lisp
#<@var{relevant-text}>
@end lisp

@noindent
where the @var{relevant-text} is object-dependent and usually describes
the object and its contents. The reader will signal an error if it
encounters a description of an object in the format @samp{#<@dots{}>}.


@node Equality Predicates, Comparison Predicates, Printed Representation, Data Types
@subsection Equality Predicates
@cindex Equality predicates
@cindex Predicates, equality

@defun eq arg1 arg2
Returns true when @var{arg1} and @var{arg2} refer to the same object.
Two objects are the same when they occupy the same place in memory and
hence modifying one object would alter the other. The following Lisp
fragments may illustrate this,

@lisp
(eq "foo" "foo")        ;the objects are distinct
    @result{} ()

(eq t t)                ;the same object -- the symbol @code{t}
    @result{} t
@end lisp

Note that the result of @code{eq} is undefined when called on two integer
objects with the same value, see @code{eql}.
@end defun

@defun equal arg1 arg2
The function @code{equal} compares the structure of the two objects
@var{arg1} and @var{arg2}. If they are considered to be equivalent then
returns true, otherwise returns false.

@lisp
(equal "foo" "foo")
    @result{} t

(equal 42 42)
    @result{} t

(equal 42 0)
    @result{} ()

(equal '(x . y) '(x . y))
    @result{} t
@end lisp
@end defun

@defun eql arg1 arg2
This function is a cross between @code{eq} and @code{equal}: if
@var{arg1} and @var{arg2} are both numbers then the value of these
numbers are compared. Otherwise it behaves in exactly the same manner
as @code{eq} does.

@lisp
(eql 3 3)
    @result{} t

(eql 1 2)
    @result{} ()

(eql "foo" "foo")
    @result{} ()

(eql 'x 'x)
    @result{} t
@end lisp
@end defun


@node Comparison Predicates, Type Predicates, Equality Predicates, Data Types
@subsection Comparison Predicates
@cindex Comparison predicates
@cindex Predicates, comparison

These functions compare their two arguments in a scalar fashion, the
arguments may be of any type but the results are only meaningful for
numbers, strings (ASCII values of each byte compared until a
non-matching pair is found then those two values are compared as
numbers) and cons cells (cars compared before cdrs).

Unlike the @code{eql} function, inexact and exact numbers will be
compared by first coercing the exact number to be inexact.

@defun = arg1 arg2 arg3 @dots{} argn
Returns true if all arguments represent the same value.
@end defun

@defun /= arg1 arg2 arg3 @dots{} argn
Returns true if no two arguments represent the same value.
@end defun

@defun > arg1 arg2 arg3 @dots{} argn
Returns true when @var{arg1} is `greater than' @var{arg2}, and
@var{arg2} is greater than @var{arg3}, and so on, upto @var{argn}.
@end defun

@defun >= arg1 arg2 arg3 @dots{} argn
Similar to @code{>}, but for the ``greater than or equal to'' relation.
@end defun

@defun < arg1 arg2 arg3 @dots{} argn
Similar to @code{>}, but for the ``less than'' relation.
@end defun

@defun <= arg1 arg2 arg3 @dots{} argn
Similar to @code{>}, but for the ``less than or equal to'' relation.
@end defun

There are two related functions for finding the maximum or minimum of a
sequence of values.

@defun max @t{#!rest} args
Return the maximum value from the list of @var{args}. When comparing
numbers, any inexact arguments cause the result to be inexact.
@end defun

@defun min @t{#!rest} args
Return the minimum value from the list of @var{args}. When comparing
numbers, any inexact arguments cause the result to be inexact.
@end defun


@node Type Predicates, Garbage Collection, Comparison Predicates, Data Types
@subsection Type Predicates
@cindex Type predicates
@cindex Predicates, type

Each type has a corresponding predicate which defines the objects which
are members of that type. Each predicate function has a single
parameter, if that parameter is of the correct type it returns
true.

@noindent
@code{integerp}, @code{numberp}, @code{null}, @code{consp},
@code{listp}, @code{vectorp}, @code{subrp}, @code{functionp},
@code{sequencep}, @code{stringp}, @code{symbolp}, @code{processp},
@code{filep}.

The documentation for these functions is with the documentation for the
relevant type.


@node Garbage Collection, , Type Predicates, Data Types
@subsection Garbage Collection
@cindex Garbage collection

In Lisp, data objects are used very freely; a side effect of this is
that it is not possible to (easily) know when an object is @dfn{stale},
that is, no references to it exist and it can therefore be reused.

The @dfn{garbage collector} is used to overcome this problem; whenever
enough memory has been allocated to make it worthwhile, evaluation
stops and the garbage collector works its way through memory deciding
which objects may still be referenced, and which are stale. The stale
objects are then recorded as being available for reuse and evaluation
continues. (But @pxref{Guardians})

@defun garbage-collect
Runs the garbage collector, usually this function doesn't need to
be called manually.
@end defun

@defvar garbage-threshold
The number of bytes of data that must have been allocated since the
last garbage collection before evaluation pauses and the garbage
collector is invoked. Its default value is about 100K.
@end defvar

@defvar idle-garbage-threshold
When the input loop is idle (due to a lack of input), this is the
number of bytes of data that must have been allocated since the garbage
collection, for another collection to be triggered.

This is usually set to a lot less than @code{garbage-threshold} since
the small delay caused by garbage collection is unnoticeable if the
system is already idle.
@end defvar

@defvar after-gc-hook
A hook (@pxref{Normal Hooks}) called immediately after each invocation
of the garbage collector.
@end defvar


@node Numbers, Sequences, Data Types, The language
@section Numbers
@cindex Numbers
@cindex Integers

@code{Librep} distinguishes between numbers that are represented
exactly and numbers that may not be. This is similar to the Scheme
dialect of Lisp. Quoting from the Scheme standard:

@quotation
@dots{} numbers are either @emph{exact} or @emph{inexact}. A number is
exact if it was written as an exact constant or was derived from exact
numbers using only exact operations. A number is inexact if it was
written as an inexact constant, if it was derived using inexact
ingredients, or if it was derived using inexact operations. Thus
inexactness is a contagious property of a number.
@end quotation

Exact numbers include both integers and rational numbers, there is no
theoretical limit to the range of the values that may be represented
@footnote{However, depending on implementation restrictions, very large
integers may be coerced to an inexact representation.}. Inexact numbers
are currently implemented using double precision floating point values.

The read syntax of any number is:
@code{[@var{pfx}@dots{}][@var{sgn}]@var{data}@dots{}}, where the
optional @var{sgn} is one of the characters @samp{-} or @samp{+},
@var{data} is the representation of the number, and @var{pfx} is zero
or more of the following prefix strings:

@table @code
@item #b
@itemx #B
Integers are described in binary,

@item #o
@itemx #O
Integers are in octal,

@item #d
@itemx #D
Integers are in decimal (the default),

@item #x
@itemx #X
Integers are in hexadecimal,

@item #e
@itemx #E
Coerce the number to an exact representation after parsing it,

@item #i
@itemx #I
Coerce to an inexact representation.
@end table

@noindent

The representation of an integer is simply the digits representing that
integer, in the radix chosen by any given prefix (defaults to decimal).
Examples of valid integer read syntaxes for the number 42 could be
@samp{42}, @samp{#x2a}, @samp{#o52}, @samp{#o+52}, @dots{}

The representation of a rational number is two sequences of digits,
separated by a @samp{/} character. For example, @samp{3/2} represents
the rational number three divided by two. 

Inexact numbers are parsed from one of two representations: decimal
point form, which is simply a decimal number containing a decimal
point, and exponential form, which is a decimal number followed by the
letter @samp{e} and a decimal exponent multiplying the first part of
the number by that power of ten. For example, @samp{10.0}, @samp{10.}
and @samp{1e1} all read as the inexact number ten. Note that the radix
prefixes currently have no effect when parsing inexact numbers, decimal
is used exclusively.

An integer's printed representation is simply the number printed in
decimal with a preceding minus sign if it is negative. Rational numbers
are printed as two integers separated by a @samp{/} character. Inexact
numbers are printed in their decimal form.

@defun numberp object
Returns true if @var{object} is a number.
@end defun

@menu
* Arithmetic Functions::
* Integer Functions::
* Rational Functions:: 
* Real Number Functions::
* Mathematical Functions::
* Bitwise Functions::
* Numeric Predicates::
* Random Numbers::
* Characters::
@end menu


@node Arithmetic Functions, Integer Functions, , Numbers
@subsection Arithmetic Functions
@cindex Arithmetic Functions
@cindex Numbers, arithmetic functions

There are a number of functions which perform arithmetic operations on
numbers, they take a varying number of values as their arguments
returning a new number as their result. When given only exact
arguments, an exact result will be returned.

@defun + number1 @t{#!rest} numbers
This functions adds its arguments then returns their sum. 
@end defun

@defun - number1 @t{#!rest} numbers
If this function is just given one argument (@var{number1}) that number is
negated and returned. Otherwise each of @var{numbers} is subtracted from
a running total starting with the value of @var{number1}.

@lisp
(- 20)
    @result{} -20

(- 20 10 5)
    @result{} 5
@end lisp
@end defun

@defun * number1 @t{#!rest} numbers
This function multiplies its arguments then returns the result.
@end defun

@defun / number1 @t{#!rest} numbers
This function performs division, a running-total (initialised from
@var{number1} is successively divided by each of @var{numbers} then
the result is returned.

@lisp
(/ 100 2)
    @result{} 50

(/ 200 2 5)
    @result{} 20

(/ 3 2)
    @result{} 3/2

(/ 3.0 2)
    @result{} 1.5
@end lisp
@end defun

@defun 1+ number
This function returns the result of adding one to @var{number}.

@lisp
(1+ 42)
    @result{} 43
@end lisp
@end defun

@defun 1- number
Returns @var{number} minus one.
@end defun


@node Integer Functions, Rational Functions, Arithmetic Functions, Numbers
@subsection Integer Functions
@cindex Integer functions
@cindex Numbers, integer functions

The functions described in this section all operate on, and return,
integer values.

@defun quotient dividend divisor
Return the integer part of dividing @var{dividend} by @var{divisor}.
@end defun

@defun remainder dividend divisor
Returns the integer remainder from dividing the @var{dividend} by
@var{divisor}. The remainder is either zero or has the same sign as
@var{dividend}.
@end defun

@defun modulo dividend divisor
@defunx mod dividend divisor
Return the value of @var{dividend} modulo @var{divisor}. Unlike the
@code{remainder} function the @code{modulo} function always has the
sign of the @var{divisor}, not of the @var{dividend}
@end defun

@defun gcd args@dots{}
Returns the greatest common divisor of the integers @var{args}@dots{}
If no arguments are given, returns zero.
@end defun

@defun lcm args@dots{}
Return the lowest common multiple of the integers @var{args}@dots{} If
no arguments are given, returns one.
@end defun


@node Rational Functions, Real Number Functions, Integer Functions, Numbers
@subsection Rational Functions
@cindex Rational functions
@cindex Numbers, rational functions

These functions operate on rational numbers.

@defun numerator x
Returns the exact numerator of @var{x}.
@end defun

@defun denominator x
Returns the exact denominator of @var{x}.
@end defun

@defun exact->inexact x
Returns an inexact version of rational number @var{x}.
@end defun


@node Real Number Functions, Mathematical Functions, Rational Functions, Numbers
@subsection Real Number Functions
@cindex Real number functions
@cindex Numbers, real number functions

@defun abs x
Returns the magnitude of @var{x}.
@end defun

@defun floor x
Round @var{x} downwards to the nearest integer less than or equal to
@var{x}.
@end defun

@defun ceiling x
Round @var{x} upwards to the nearest integer less than or equal to
@var{x}.
@end defun

@defun truncate x
Round @var{x} to the nearest integer between @var{x} and zero.
@end defun

@defun round x
Round @var{x} to the nearest integer. Halfway cases are rounded to the
nearest even integer.
@end defun

@defun inexact->exact x
Returns an exact representation of @var{x}. This may involve a loss of
accuracy.
@end defun


@node Mathematical Functions, Bitwise Functions, Real Number Functions, Numbers
@subsection Mathematical Functions
@cindex Mathematical functions
@cindex Numbers, mathematical functions

@defun exp x
Return `e' (the base of natural logarithms) raised to the power
@var{x}.
@end defun

@defun log x
Return the natural logarithm of @var{x}. An arithmetic error is
signalled if @var{x} is less than zero.
@end defun

@defun sin x
Return the sine of angle @var{x}; x is in terms of radians.
@end defun

@defun cos x
Return the cosine of angle @var{x}.
@end defun

@defun tan x
Return the tangent of angle @var{x}.
@end defun

@defun asin x
Return the arc sine of @var{x} (the value whose sine is @var{x}), in
radians.
@end defun

@defun acos x
Return the arc cosine of @var{x}.
@end defun

@defun atan x
Return the arc tangent of @var{x}.
@end defun

@defun sqrt x
Return the non-negative square root of @var{x}. Currently, if @var{x}
is negative, an arithmetic error is signalled.
@end defun

@defun expt x y
Returns @var{x} raised to the power @var{y}.

If @var{x} is negative and @var{y} is a non-integer, then an arithmetic
error is signalled (mathematically should return a complex number).
@end defun


@node Bitwise Functions, Numeric Predicates, Mathematical Functions, Numbers
@subsection Bitwise Functions
@cindex Bitwise functions
@cindex Numbers, bitwise functions

These functions operate on the bit string which an integer represents,
assuming a two's complement representation.

@defun lsh number count
This function shifts the integer @var{number} @var{count} bits to the
left, if @var{count} is negative @var{number} is shifted to the right
instead.

@lisp
(lsh 1 8)
    @result{} 256

(lsh 256 -8)
    @result{} 1
@end lisp
@end defun

@defun logand number1 @t{#!rest} numbers
This function uses a bit-wise logical `and' operation to combine all its
arguments (there must be at least one argument).

@lisp
(logand 15 8)
    @result{} 8

(logand 15 7 20)
    @result{} 4
@end lisp
@end defun

@defun logior number1 @t{#!rest} numbers
Uses a bit-wise logical `inclusive-or' to combine all its arguments (there
must always be at least one argument).

@lisp
(logior 1 2 4)
    @result{} 7
@end lisp
@end defun

@defun logxor number1 @t{#!rest} numbers
Uses a bitwise logical `exclusive-or' to combine all its arguments
(there must be at least one).

@lisp
(logxor 7 3)
    @result{} 4
@end lisp
@end defun

@defun lognot number
This function inverts all the bits in @var{number}.

@lisp
(lognot 0)
    @result{} -1

(lognot 2)
    @result{} -3

(lognot -1)
    @result{} 0
@end lisp
@end defun


@node Numeric Predicates, Random Numbers, Bitwise Functions, Numbers
@subsection Numeric Predicates
@cindex Numeric predicates
@cindex Numbers, predicates on
@cindex Predicates on numbers

For the documentation of the functions @code{=}, @code{/=}, @code{>},
@code{<}, @code{>=}, @code{<=}, @code{max} and @code{min}, see
@ref{Comparison Predicates}.

@defun exactp object
Returns true when @var{object} is an exact number.
@end defun

@defun inexactp object
Returns true when @var{object} is an inexact number.
@end defun

@defun integerp object
Returns true when @var{object} is an integer.
@end defun

@defun rationalp object
Returns true when @var{object} is a rational number (including
integers).
@end defun

@defun realp object
Returns true when @var{object} is a real number.
@end defun

@defun oddp x
Return true if @var{x} is an odd number.
@end defun

@defun evenp x
Return true if @var{x} is an even number.
@end defun

@defun positivep x
Return true if @var{x} is a number greater than zero.
@end defun

@defun negativep x
Return true if @var{x} is a number less than zero.
@end defun

@defun zerop x
Returns true if @var{x} is equal to zero.
@end defun


@node Random Numbers, Characters, Numeric Predicates, Numbers
@subsection Pseudo-Random Numbers
@cindex Pseudo-random numbers
@cindex Random numbers
@cindex Numbers, pseudo random

The @code{random} function allows pseudo-random numbers to be
generated.

@defun random @t{#!optional} limit
Return a pseudo-random number between zero and @var{limit}-1 inclusive.
If @var{limit} is undefined, it is taken as being the largest positive
integer representable in a fixnum.

Calling @code{random} with @var{limit} equal to the symbol @code{t}
seeds the generator with the current time of day.
@end defun


@node Characters, , Random Numbers, Numbers
@subsection Characters
@cindex Characters

In @code{librep} characters are stored in integers. Their read syntax
is a question mark followed by the character itself, which may be an
escape sequence introduced by a backslash. For details of the available
escape sequences see @ref{Strings}.

@lisp
?a
    @result{} 97

?\n
    @result{} 10

?\177
    @result{} 127
@end lisp

@defun alpha-char-p character
This function returns true when @var{character} is one of the
alphabetic characters.

@lisp
(alpha-char-p ?a)
    @result{} t
@end lisp
@end defun

@defun upper-case-p character
When @var{character} is one of the upper-case characters this function
returns true.
@end defun

@defun lower-case-p character
Returns true when @var{character} is lower-case.
@end defun

@defun digit-char-p character
This function returns true when @var{character} is one of the decimal
digit characters.
@end defun

@defun alphanumericp character
This function returns true when @var{character} is either an alphabetic
character or a decimal digit character.
@end defun

@defun space-char-p character
Returns true when @var{character} is a white-space character (space, tab,
newline or form feed).
@end defun

@defun char-upcase character
This function returns the upper-case equivalent of @var{character}. If
@var{character} is already upper-case or has no upper-case equivalent it
is returned unchanged.

@lisp
(char-upcase ?a)
    @result{} 65                       ;`A'

(char-upcase ?A)
    @result{} 65                       ;`A'

(char-upcase ?!)
    @result{} 33                       ;`!'
@end lisp
@end defun

@defun char-downcase character
Returns the lower-case equivalent of the character @var{character}.
@end defun


@node Sequences, Symbols, Numbers, The language
@section Sequences
@cindex Sequences
@cindex Arrays

Sequences are ordered groups of objects, there are several primitive
types which can be considered sequences, each with their pros and cons.

A sequence is either an array or a list, where an array is either a vector
or a string.

@defun sequencep object
This function returns true if @var{object} is a sequence.
@end defun

@menu
* Cons Cells::                  An ordered pair of two objects
* Lists::                       Chains of cons cells
* Vectors::                     A chunk of memory holding a number of objects
* Strings::                     Strings are efficiently-stored vectors
* Array Functions::             Accessing elements in vectors and strings
* Sequence Functions::          These work on any type of sequence
@end menu


@node Cons Cells, Lists, , Sequences
@subsection Cons Cells
@cindex Cons cells
@cindex Sequences, cons cells

A @dfn{cons cell} is an ordered pair of two objects, the @dfn{car} and
the @dfn{cdr}.

The read syntax of a cons cell is an opening parenthesis followed by the
read syntax of the car, a dot, the read syntax of the cdr and a closing
parenthesis. For example a cons cell with a car of 10 and a cdr of
the string @samp{foo} would be written as,

@lisp
(10 . "foo")
@end lisp

@defun cons car cdr
This function creates a new cons cell. It will have a car of @var{car} and
a cdr of @var{cdr}.

@lisp
(cons 10 "foo")
    @result{} (10 . "foo")
@end lisp
@end defun

@defun consp object
This function returns true if @var{object} is a cons cell.

@lisp
(consp '(1 . 2))
    @result{} t

(consp '())
    @result{} ()

(consp (cons 1 2))
    @result{} t
@end lisp
@end defun

The strange syntax @samp{'(1 . 2)} is known as @dfn{quoting}
(@pxref{Quoting}), it tells the evaluator that the object following the
quote-mark is a constant, and therefore should not be evaluated. This
will be explained in more detail later.

@cindex Atom
In Lisp an @dfn{atom} is any object which is not a cons cell (and is,
therefore, atomic).

@defun atom object
Returns true if @var{object} is an atom (not a cons cell).
@end defun

Given a cons cell there are a number of operations which can be performed
on it.

@defun car cons-cell
This function returns the object which is the car (first element) of
the cons cell @var{cons-cell}.

@lisp
(car (cons 1 2))
    @result{} 1

(car '(1 . 2))
    @result{} 1
@end lisp
@end defun

@defun cdr cons-cell
This function returns the cdr (second element) of the cons cell
@var{cons-cell}.

@lisp
(cdr (cons 1 2))
    @result{} 2

(cdr '(1 . 2))
    @result{} 2
@end lisp
@end defun

@defun rplaca cons-cell new-car
This function sets the value of the car (first element) in the cons
cell @var{cons-cell} to @var{new-car}. The value returned is
@var{cons-cell}.

@lisp
(setq x (cons 1 2))
    @result{} (1 . 2)
(rplaca x 3)
    @result{} (3 . 2)
x
    @result{} (3 . 2)
@end lisp
@end defun

@defun rplacd cons-cell new-cdr
This function is similar to @code{rplacd} except that the cdr slot
(second element) of @var{cons-cell} is modified.
@end defun


@node Lists, Vectors, Cons Cells, Sequences
@subsection Lists
@cindex Lists

A list is a sequence of zero or more objects, the main difference between
lists and vectors is that lists are more dynamic: they can change size,
be split, reversed, concatenated, etc@dots{} very easily.

In Lisp lists are not a primitive type; instead singly-linked lists are
formed by chaining cons cells together (@pxref{Cons Cells}). The empty
list is represented by the special value @code{()}.

@defun listp arg
This functions returns true when its argument, @var{arg}, is a
list (i.e. either a cons cell or @code{()}).
@end defun

@defun null arg
Returns a true value if @var{arg} is the empty list.
@end defun

@menu
* List Structure::              How lists are built from cons cells
* Building Lists::              Dynamically creating lists
* Accessing List Elements::     Getting at the elements which make the list
* Modifying Lists::             How to alter the contents of a list
* Association Lists::           Lists can represent relations
* Infinite Lists::              Circular data structures in Lisp
@end menu


@node List Structure, Building Lists, , Lists
@subsubsection List Structure
@cindex List structure

Each element in a list is given its own cons cell and stored in the car
of that cell. The list is then constructed by having the cdr of a cell
point to the cons cell containing the next element (and hence the
entire rest of the list). The cdr of the cell containing the last
element in the list is @code{()}. A list of zero elements is
represented by @code{()}.

The read syntax of a list is an opening parenthesis, followed by the
read syntax of zero or more space-separated objects, followed by a
closing parenthesis. Alternatively, lists can be constructed `manually'
using dotted-pair notation.

All of the following examples result in the same list of five elements:
the numbers from zero to four.

@lisp
(0 1 2 3 4)

(0 . (1 . (2 . (3 . (4 . ())))))

(0 1 2 . (3 4))
@end lisp

An easy way to visualise lists and how they are constructed is to see
each cons cell in the list as a separate @dfn{box} with pointers to its
car and cdr,

@example
+-----+-----+
|  o  |  o----> cdr
+--|--+-----+
   |
    --> car
@end example

Complex box-diagrams can now be drawn to represent lists. For example the
following diagram represents the list @code{(1 2 3 4)}.

@example
+-----+-----+   +-----+-----+   +-----+-----+   +-----+-----+
|  o  |  o----> |  o  |  o----> |  o  |  o----> |  o  |  o----> ()
+--|--+-----+   +--|--+-----+   +--|--+-----+   +--|--+-----+
   |               |               |               |
    --> 1           --> 2           --> 3           --> 4
@end example

A more complex example, the list @code{((1 2) (foo bar))} can be drawn as,

@example
+-----+-----+                          +-----+-----+
|  o  |  o---------------------------> |  o  |  o----> ()
+--|--+-----+                          +--|--+-----+
   |                                      |
+-----+-----+   +-----+-----+          +-----+-----+   +-----+-----+
|  o  |  o----> |  o  |  o----> ()     |  o  |  o----> |  o  |  o----> ()
+--|--+-----+   +--|--+-----+          +--|--+-----+   +--|--+-----+
   |               |                      |               |
    --> 1           --> 2                  --> foo         --> bar
@end example


@node Building Lists, Accessing List Elements, List Structure, Lists
@subsubsection Building Lists
@cindex Building lists
@cindex Lists, building

It has already been described how you can create lists using the Lisp
reader; this method does have a drawback though: the list created is
effectively static. If you modify the contents of the list and that
list was created when a function was defined the list will remain
modified for all future invocations of that function. This is not
usually a good idea, consider the following function definition,

@lisp
(defun bogus-function (x)
  "Return a list whose first element is nil and whose second element is X."
  (let
      ((result '(nil nil)))     ;Static list which is filled in each time
    (rplaca (cdr result) x)     ; the function is called
    result))
@end lisp

@noindent
This function does in fact do what its documentation claims, but a
problem arises when it is called more than once,

@lisp
(setq x (bogus-function 'foo))
    @result{} (nil foo)
(setq y (bogus-function 'bar))
    @result{} (nil bar)               ;The first result has been destroyed
x
    @result{} (nil bar)               ;See!
@end lisp

This example is totally contrived---no one would ever write a
function like the one in the example but it does demonstrate the need
for a dynamic method of creating lists.

@defun list @t{#!rest} elements
This function creates a list out of its arguments, if zero arguments are
given the empty list, @code{()}, is returned.

@lisp
(list 1 2 3)
    @result{} (1 2 3)

(list (major-version-number) (minor-version-number))
    @result{} (3 2)

(list)
    @result{} ()
@end lisp
@end defun

@defun list* arg1 arg2 @dots{} argn-1 argn
Creates a new list @code{(@var{arg1} @var{arg2} @dots{} @var{argn-1} .
@var{argn})}.

@lisp
(list* 1 2 '(3 4))
    @result{} (1 2 3 4)
@end lisp
@end defun

@defun make-list length @t{#!optional} initial-value
This function creates a list @var{length} elements long. If the
@var{initial-value} argument is given it defines the value of all
elements in the list, if it is not defined they are all @code{()}.

@lisp
(make-list 2)
    @result{} (() ())

(make-list 3 t)
    @result{} (t t t)

(make-list 0)
    @result{} ()
@end lisp
@end defun

@defun append @t{#!rest} lists
This function creates a new list with the elements of each of its arguments
(which must be lists). Unlike the function @code{nconc} this function
preserves the structure of all its arguments.

@lisp
(append '(1 2 3) '(4 5))
    @result{} (1 2 3 4 5)

(append)
    @result{} ()
@end lisp

What actually happens is that all arguments but the last are copied,
then the last argument is linked on to the end of the list (uncopied).

@lisp
(setq foo '(1 2))
    @result{} (1 2)
(setq bar '(3 4))
    @result{} (3 4)
(setq baz (append foo bar))
    @result{} (1 2 3 4)
(eq (nthcdr 2 baz) bar)
    @result{} t
@end lisp

The following diagram shows the final state of the three variables more
clearly,

@example
foo--> +-----+-----+   +-----+-----+
       |  o  |  o----> |  o  |     |
       +--|--+-----+   +--|--+-----+
          |               |
          o--> 1          o--> 2   bar
          |               |          ->
baz--> +--|--+-----+   +--|--+-----+   +-----+-----+   +-----+-----+
       |  o  |  o----> |  o  |  o----> |  o  |  o----> |  o  |     |
       +-----+-----+   +-----+-----+   +--|--+-----+   +--|--+-----+
                                          |               |
                                           --> 3           --> 4
@end example

Note how @code{foo} and the first half of @code{baz} use the @emph{same}
objects for their elements---copying a list only copies its cons cells, its
elements are reused. Also note how the variable @code{bar} actually
references the mid-point of @code{baz} since the last list in an @code{append}
call is not copied.
@end defun

@defun remove elt list
Return a copy of @var{list}, with all elements the same as @var{elt}
discarded (using the @code{equal} function to compare).
@end defun

@defun remq elt list
Similar to the @code{remove} function, except that comparisons are made
using @code{eq}.
@end defun

@defun reverse list
This function returns a new list; it is made from the elements of the list
@var{list} in reverse order. Note that this function does not alter its
argument.

@lisp
(reverse '(1 2 3 4))
    @result{} (4 3 2 1)
@end lisp
@end defun

As a postscript to this section, the function used as an example at the
beginning could now be written as,

@lisp
(defun not-so-bogus-function (x)
  (list nil x))
@end lisp

Also note that the @code{cons} function can be used to create lists by hand
and to add new elements onto the front of a list. For example:

@lisp
(setq x (list 1 2 3))
    @result{} (1 2 3)
(setq x (cons 0 x))
    @result{} (0 1 2 3)
@end lisp


@node Accessing List Elements, Modifying Lists, Building Lists, Lists
@subsubsection Accessing List Elements
@cindex Accessing list elements
@cindex Lists, accessing elements

The most flexible method of accessing an element in a list is via a
combination of the @code{car} and @code{cdr} functions. There are other
functions which provide an easier way to get at the elements in a flat
list. These will usually be faster than a string of @code{car} and
@code{cdr} operations.

@defun nth count list
This function returns the element @var{count} elements down the list,
therefore to access the first element use a @var{count} of zero (or even
better the @code{car} function). If there are too few elements in the list
and no element number @var{count} can be found @code{()} is returned.

@lisp
(nth 3 '(0 1 2 3 4 5))
    @result{} 3

(nth 0 '(foo bar)
    @result{} foo
@end lisp
@end defun

@defun nthcdr count list
This function takes the cdr of the list @var{list} @var{count} times,
returning the last cdr taken.

@lisp
(nthcdr 3 '(0 1 2 3 4 5))
    @result{} (3 4 5)

(nthcdr 0 '(foo bar))
    @result{} (foo bar)
@end lisp
@end defun

@defun last list
This function returns the last element in the list @var{list}. If the
list has zero elements @code{()} is returned.

@lisp
(last '(1 2 3))
    @result{} 3

(last '())
    @result{} ()
@end lisp
@end defun

@defun member object list
This function scans through the list @var{list} until it finds an element
which is @code{equal} to @var{object}. The tail of the list (the cons cell
whose car is the matched object) is then returned. If no elements match
@var{object} then the empty list @code{()} is returned.

@lisp
(member 'c '(a b c d e))
    @result{} (c d e)

(member 20 '(1 2))
    @result{} ()
@end lisp
@end defun

@defun memq object list
This function is similar to @code{member} except that comparisons are
performed by the @code{eq} function not @code{equal}.
@end defun

@node Modifying Lists, Association Lists, Accessing List Elements, Lists
@subsubsection Modifying Lists
@cindex Modifying lists
@cindex Lists, modifying

The @code{nthcdr} function can be used in conjunction with the @code{rplaca}
function to modify an arbitrary element in a list. For example,

@lisp
(rplaca (nthcdr 2 '(0 1 2 3 4 5)) 'foo)
    @result{} foo
@end lisp

@noindent
sets the third element of the list @code{(0 1 2 3 4 5)} to the symbol
called @code{foo}.

There are also functions which modify the structure of a whole list. These
are called @dfn{destructive} operations because they modify the actual
structure of a list---no copy is made. This can lead to unpleasant
side effects if care is not taken.

@defun nconc @t{#!rest} lists
This function is the destructive equivalent of the function @code{append},
it modifies its arguments so that it can return a list which is the
concatenation of the elements in its arguments lists.

Like all the destructive functions this means that the lists given as
arguments are modified (specifically, the cdr of their last cons cell
is made to point to the next list). This can be seen with the
following example (similar to the example in the @code{append} documentation).

@lisp
(setq foo '(1 2))
    @result{} (1 2)
(setq bar '(3 4))
    @result{} (3 4)
(setq baz (nconc foo bar))
    @result{} (1 2 3 4)
foo
    @result{} (1 2 3 4)                ;`foo' has been altered!
(eq (nthcdr 2 baz) bar)
    @result{} t
@end lisp

The following diagram shows the final state of the three variables more
clearly,

@example
foo-->                           bar-->
baz--> +-----+-----+   +-----+-----+   +-----+-----+   +-----+-----+
       |  o  |  o----> |  o  |  o----> |  o  |  o----> |  o  |     |
       +--|--+-----+   +--|--+-----+   +--|--+-----+   +--|--+-----+
          |               |               |               |
           --> 1           --> 2             --> 3           --> 4
@end example
@end defun

@defun nreverse list
This function rearranges the cons cells constituting the list @var{list}
so that the elements are in the reverse order to what they were.

@lisp
(setq foo '(1 2 3))
    @result{} (1 2 3)
(nreverse foo)
    @result{} (3 2 1)
foo
    @result{} (1)                      ;`foo' wasn't updated when the list
                                ; was altered.
@end lisp
@end defun

@defun delete object list
This function destructively removes all elements of the list @var{list}
which are @code{equal} to @var{object} then returns the modified list.

@lisp
(delete 1 '(0 1 0 1 0))
    @result{} (0 0 0)
@end lisp

When this function is used to remove an element from a list which is stored
in a variable that variable must be set to the return value of the
@code{delete} function. Otherwise, if the first element of the list
has to be deleted (because it is @code{equal} to @var{object}) the value
of the variable will not change.

@lisp
(setq foo '(1 2 3))
    @result{} (1 2 3)
(delete 1 foo)
    @result{} (2 3)
foo
    @result{} (1 2 3)
(setq foo (delete 1 foo))
    @result{} (2 3)
@end lisp
@end defun

@defun delq object list
This function is similar to the @code{delete} function, the only difference
is that the @code{eq} function is used to compare @var{object} with each
of the elements in @var{list}, instead of the @code{equal} function which
is used by @code{delete}.
@end defun

@defun sort list @t{#!optional} predicate
Destructively sorts (i.e. by modifying cdrs) the list of values
@var{list}, to satisfy the function @var{predicate}, returning the
sorted list. If @var{predicate} is undefined, the @code{<} function is
used, sorting the list into ascending order.

@var{predicate} is called with two values, it should return true if
the first is considered less than the second.

@lisp
(sort '(5 3 7 4))
    @result{} (3 4 5 7)
@end lisp

The sort is stable, in that elements in the list which are equal will
preserve their original positions in relation to each other.
@end defun


@node Association Lists, Infinite Lists, Modifying Lists, Lists
@subsubsection Association Lists
@cindex Association lists
@cindex Alists
@cindex Lists, association

An @dfn{association list} (or @dfn{alist}) is a list mapping keys to
to. Each element of the alist is a cons cell, the car of which is the
@dfn{key}, the cdr the value that it associates to. For example an
alist could look like,

@lisp
((fred . 20)
 (bill . 30))
@end lisp

@noindent
this alist has two keys, @code{fred} and @code{bill} which both associate
to an integer (20 and 30 respectively).

It is possible to make the associated values lists, this looks like,

@lisp
((fred 20 male)
 (bill 30 male)
 (sue  25 female))
@end lisp

@noindent
in this alist the symbol @code{fred} is associated with the list
@code{(20 male)}.

There are a number of functions which let you interrogate an alist with
a given key for its association.

@defun assoc key alist
This function scans the association list @var{alist} for the first element
whose car is @code{equal} to @var{key}, this element is then returned. If
no match of @var{key} is found false is returned.

@lisp
(assoc 'two '((one . 1) (two . 2) (three . 3)))
    @result{} (two . 2)
@end lisp
@end defun

@defun assq key alist
Similar to the function @code{assoc} except that the function @code{eq} is
used to compare elements instead of @code{equal}.

It is not usually wise to use @code{assq} when the keys of the alist may not
be symbols---@code{eq} won't think two objects are equivalent unless they
are the @emph{same} object!

@lisp
(assq "foo" '(("bar" . 1) ("foo" . 2)))
    @result{} ()
(assoc "foo" '(("bar" . 1) ("foo" . 2)))
    @result{} ("foo" . 2)
@end lisp
@end defun

@defun rassoc association alist
This function searches through @var{alist} until it finds an element whose
cdr is @code{equal} to @var{association}, that element is then returned.
false will be returned if no elements match.

@lisp
(rassoc 2 '((one . 1) (two . 2) (three . 3)))
    @result{} (two . 2)
@end lisp
@end defun

@defun rassq association alist
This function is equivalent to @code{rassoc} except that it uses @code{eq}
to make comparisons.
@end defun


@node Infinite Lists, , Association Lists, Lists
@subsubsection Infinite Lists
@cindex Infinite lists
@cindex Circular lists
@cindex Lists, circular

Sometimes it is useful to be able to create `infinite' lists---that is,
lists which appear to have no last element---this can easily be done
in Lisp by linking the cdr of the last cons cell in the list structure
back to the beginning of the list.

@example
 ----------------------------------- 
|                                   |
 --> +-----+-----+   +-----+-----+  |
     |  o  |  o----> |  o  |  o----- 
     +--|--+-----+   +--|--+-----+
        |               |
         --> 1           --> 2
@end example

The diagram above represents the infinite list @code{(1 2 1 2 1 2 @dots{})}.

Infinite lists have a major drawback though, many of the standard list
manipulation functions can not be used on them. These functions work by
moving through the list until they reach the end. If the list has @emph{no}
end the function may never terminate and the only option is to send the
interpreter an interrupt signal.

The only functions which may be used on circular lists are: the cons
cell primitives (@code{cons}, @code{car}, @code{cdr}, @code{rplaca},
@code{rplacd}), @code{nth} and @code{nthcdr}.

Also note that infinite lists can't be printed. But note the
@code{print-length} and @code{print-level} variables, see @ref{Output
Functions}. 


@node Vectors, Strings, Lists, Sequences
@subsection Vectors

A vector is a fixed-size sequence of Lisp objects, each element may be
accessed in constant time---unlike lists where the time taken to access
an element is proportional to the position of the element.

The read syntax of a vector is an opening square bracket, followed by zero
or more space-separated objects, followed by a closing square bracket. For
example,

@lisp
[zero one two three]
@end lisp

In general it is best to use vectors when the number of elements to be
stored is known and lists when the sequence may grow or shrink.

@defun vectorp object
This function returns true if its argument, @var{object}, is a vector.
@end defun

@defun vector @t{#!rest} elements
This function creates a new vector containing the arguments given to the
function.

@lisp
(vector 1 2 3)
    @result{} [1 2 3]

(vector)
    @result{} []
@end lisp
@end defun

@defun make-vector size @t{#!optional} initial-value
Returns a new vector, @var{size} elements big. If @var{initial-value} is
defined each element of the new vector is set to @var{initial-value}, otherwise
they are all @code{()}.

@lisp
(make-vector 4)
    @result{} [() () () ()]

(make-vector 2 t)
    @result{} [t t]
@end lisp
@end defun


@node Strings, Array Functions, Vectors, Sequences
@subsection Strings

A string is a vector of characters (@pxref{Characters}), they are
generally used for storing and manipulating pieces of text.
@code{librep} puts no restrictions on the values which may be stored in
a string---specifically, the null character (@samp{^@@}) may be
stored with no problems.

The read syntax of a string is a double quote character, followed by the
contents of the string, the object is terminated by a second double quote
character. For example, @code{"abc"} is the read syntax of the string
@samp{abc}.

@cindex Escape sequences in strings
@cindex Strings, escape sequences
Any backslash characters in the string's read syntax introduce an escape
sequence; one or more of the following characters are treated specially to
produce the next @emph{actual} character in the string.

The following escape sequences are supported (all are shown without their
leading backslash @samp{\} character).

@table @samp
@item n
A newline character.

@item r
A carriage return character.

@item f
A form feed character.

@item t
A TAB character.

@item a
A `bell' character (this is Ctrl-g).

@item \
A backslash character.

@item ^@var{c}
The `control' code of the character @var{c}. This is calculated by toggling
the seventh bit of the @emph{upper-case} version of @var{c}.

For example,

@lisp
\^C             ;A Ctrl-c character (ASCII value 3)
\^@@            ;The NUL character (ASCII value 0)
@end lisp

@item 012
The character whose ASCII value is the octal value @samp{012}. After the
backslash character the Lisp reader reads up to three octal digits and
combines them into one character.

@item x12
The character whose ASCII value is the hexadecimal value @samp{12}, i.e.
an @samp{x} character followed by one or two hex digits.
@end table

@defun stringp object
This function returns true if its argument is a string.
@end defun

@defun make-string length @t{#!optional} initial-character
Creates a new string containing @var{length} characters, each character
is initialised to @var{initial-character} (or to spaces if
@var{initial-character} is not defined).

@lisp
(make-string 3)
    @result{} "   "

(make-string 2 ?$)
    @result{} "$$"
@end lisp
@end defun

@defun concat @t{#!rest} args
This function concatenates all of its arguments, @var{args}, into a single
string which is returned. If no arguments are given then the null string
(@samp{}) results.

Each of the @var{args} may be a string, a character or a list or vector of
characters. Characters are stored in strings modulo 256.

@lisp
(concat "foo" "bar")
    @result{} "foobar"

(concat "a" ?b)
    @result{} "ab"

(concat "foo" [?b ?a ?r])
    @result{} "foobar"

(concat)
    @result{} ""
@end lisp
@end defun

@defun substring string start @t{#!optional} end
This function creates a new string which is a partial copy of the string
@var{string}. The first character copied is @var{start} characters from
the beginning of the string. If the @var{end} argument is defined it is
the index of the character to stop copying at, if it is not defined
all characters until the end of the string are copied.

@lisp
(substring "xxyfoozwx" 3 6)
    @result{} "foo"

(substring "xyzfoobar" 3)
    @result{} "foobar"
@end lisp
@end defun

@defun string= string1 string2
This function compares the two strings @var{string1} and
@var{string2}---if they are made from the same characters in the same
order then true is returned.

@lisp
(string= "one" "one")
    @result{} t

(string= "one" "two")
    @result{} ()
@end lisp

Note that an alternate way to compare strings (or anything!) is to use the
@code{equal} function.
@end defun

@defun string-equal string1 string2
Returns true if @var{string1} and @var{string2} are the same,
ignoring differences in character case.
@end defun

@defun string< string1 string2
This function returns true if @var{string1} is `less' than @code{string2}.
This is determined by comparing the two strings a character at a time, the
first pair of characters which do not match each other are then compared
with a normal `less-than' function.

In @code{librep} the standard @code{<} function understands strings so
@code{string<} is just a macro calling that function.

@lisp
(string< "abc" "abd")
    @result{} t

(string< "abc" "abb")
    @result{} ()
@end lisp
@end defun

@defun string-lessp string1 string2
Similar to @code{string<} but ignores character case in comparisons.
@end defun

See @ref{String Functions} for a few more string manipulating
functions, and @ref{Regular Expressions} for a method of pattern
matching in strings.


@node Array Functions, Sequence Functions, Strings, Sequences
@subsection Array Functions
@cindex Array functions

@defun arrayp object
This function returns true if @var{object} is an array.
@end defun

@defun aref array position
Returns the element of the array (vector or string) @var{array} @var{position}
elements from the first element (i.e. the first element is numbered zero).
If no element exists at @var{position} in @var{array}, false is
returned.

@lisp
(aref [0 1 2 3] 2)
    @result{} 2

(aref "abcdef" 3)
    @result{} 100                      ;`d'
@end lisp
@end defun

@defun aset array position value
This function sets the element of the array @var{array} with an index of
@var{position} (counting from zero) to @var{value}. An error is signalled
if element @var{position} does not exist. The result of the function is
@var{value}.

@lisp
(setq x [0 1 2 3])
    @result{} [0 1 2 3]
(aset x 2 'foo)
    @result{} foo
x
    @result{} [0 1 foo 3]
@end lisp
@end defun


@node Sequence Functions, , Array Functions, Sequences
@subsection Sequence Functions
@cindex Sequence functions

@defun sequencep arg
Returns true if @var{arg} is a sequence, i.e. a list or an array.
@end defun

@defun length sequence
This function returns the length (an integer) of the sequence @var{sequence}.

@lisp
(length "abc")
    @result{} 3

(length '(1 2 3 4))
    @result{} 4

(length [x y])
    @result{} 2
@end lisp
@end defun

@defun copy-sequence sequence
Returns a new copy of the sequence @var{sequence}. Where possible (in lists
and vectors) only the `structure' of the sequence is newly allocated: the
same objects are used for the elements in both sequences.

@lisp
(copy-sequence "xy")
    @result{} "xy"

(setq x '("one" "two"))
    @result{} ("one" "two")
(setq y (copy-sequence x))
    @result{} ("one" "two")
(eq x y)
    @result{} ()
(eq (car x) (car y))
    @result{} t
@end lisp
@end defun

@defun elt sequence position
This function returns the element of @var{sequence} @var{position} elements
from the beginning of the sequence.

This function is a combination of the @code{nth} and @code{aref} functions.

@lisp
(elt [0 1 2 3] 1)
    @result{} 1

(elt '(foo bar) 0)
    @result{} foo
@end lisp
@end defun


@node Symbols, Evaluation, Sequences, The language
@section Symbols
@cindex Symbols

Symbols are objects with a name (almost always a unique name). They are
one of the most important data types in Lisp since they are used to
provided named variables (@pxref{Variables}) and functions
(@pxref{Functions}).

@defun symbolp arg
This function returns true when its argument is a symbol.
@end defun

@menu
* Symbol Syntax::               The read syntax of symbols
* Symbol Attributes::           The objects stored in a symbol
* Obarrays::                    Vectors used to store symbols
* Creating Symbols::            Allocating new symbols
* Interning::                   Putting a symbol into an obarray
* Property Lists::              Each symbol has a set of properties
* Keyword Symbols::             Self-evaluating keywords
@end menu


@node Symbol Syntax, Symbol Attributes, , Symbols
@subsection Symbol Syntax
@cindex Symbol syntax

The read syntax of a symbol is usually its name; however, if the name
contains any meta-characters (whitespace or any from @samp{()[]'";|\})
they will have to be entered specially. There are two ways to tell the
reader that a meta-character is actually part of the symbol's name:

@enumerate
@item
Precede the meta-character by a backslash character (@samp{\}), for
example:

@lisp
xy\(z\)                 ;the symbol whose name is @samp{xy(z)}
@end lisp

@item
Enclose part of the name in vertical bars (two @samp{|} characters).
All characters after the starting vertical line are copied as-is until
the closing vertical line is encountered. For example:

@lisp
xy|(z)|                 ;the symbol @samp{xy(z)}
@end lisp
@end enumerate

Here are some example read syntaxes.

@lisp
setq                    ; @samp{setq}
|setq|                  ; @samp{setq}
\s\e\t\q                ; @samp{setq}
1                       ; the @emph{number} 1
\1                      ; the @emph{symbol} @samp{1}
|!$%zf78&|              ; @samp{!$%zf78&}
foo|(bar)|              ; @samp{foo(bar)}
foo\(bar\)              ; @samp{foo(bar)}
@end lisp


@node Symbol Attributes, Obarrays, Symbol Syntax, Symbols
@subsection Symbol Attributes
@cindex Symbol attributes

All symbols have two basic attributes: print name and property list.
Most important is the @dfn{print name} of the symbol. This is a string
naming the symbol, after it has been defined (when the symbol is first
created) it may not be changed.

@defun symbol-name symbol
This function returns the print name of the symbol @var{symbol}.

@lisp
(symbol-name 'unwind-protect)
    @result{} "unwind-protect"
@end lisp
@end defun

The symbol's @dfn{property list} (or plist) is similar to an alist
(@pxref{Association Lists}), though stored differently, and provides a
method of storing arbitrary extra values in each symbol. @xref{Property
Lists}.

Although not strictly an attribute of the symbol, symbols also provide
a means of associating values with names (i.e. variables). Within a
defined context, a symbol may have a @dfn{binding}, this binding
associates the symbol with a memory location within which a value may
be stored. When writing Lisp programs, the value of a symbol's current
binding is accessed by writing the print name of the symbol. Similarly
the binding may be modified by using the @code{setq} special form.
@xref{Variables}.


@node Obarrays, Creating Symbols, Symbol Attributes, Symbols
@subsection Obarrays
@cindex Obarrays
@cindex Symbols, obarrays

An @dfn{obarray} is the structure used to ensure that no two symbols
have the same name and to provide quick access to a symbol given its
name. An obarray is a vector, each element of the vector is a chain of
symbols whose names share the same hash-code (a @dfn{bucket}). These
symbols are chained together through links which are invisible to Lisp
programs: if you examine an obarray you will see that each bucket looks
as though it has at most one symbol stored in it.

The normal way to reference a symbol is simply to type its name in the
program, when the Lisp reader encounters a name of a symbol it looks
in the default obarray for a symbol of that name. If the named symbol
doesn't exist it is created and hashed into the obarray---this
process is known as @dfn{interning} the symbol, for more details see
@ref{Interning}.

@defvar obarray
This variable contains the obarray that the @code{read} function uses when
interning symbols.
@end defvar

@defun make-obarray size
This function creates a new obarray with @var{size} hash buckets (this
should probably be a prime number for the fewest hash collisions).

This is the only way of creating an obarray. @code{make-vector} is
@emph{not suitable}.
@end defun

@defun find-symbol symbol-name @t{#!optional} obarray
This function scans the specified obarray (@var{obarray} or the value of
the variable @code{obarray} if @var{obarray} is undefined) for a symbol
whose name is the string @var{symbol-name}. The value returned is the
symbol if it can be found or false otherwise.

@lisp
(find-symbol "setq")
    @result{} setq
@end lisp
@end defun

@defun apropos regexp @t{#!optional} predicate obarray
Returns a list of symbols from the obarray @var{obarray} (or the
default) whose print name matches the regular expression @var{regexp}
(@pxref{Regular Expressions}). If @var{predicate} is true, each symbol
which matches @var{regexp} is applied to the function @var{predicate},
if the value is true it is considered a match.

The @var{predicate} argument is useful for restricting matches to a
certain type of symbol, for example only commands.

@lisp
(apropos "^yank" 'commandp)
    @result{} (yank-rectangle yank yank-to-mouse)
@end lisp
@end defun


@node Creating Symbols, Interning, Obarrays, Symbols
@subsection Creating Symbols
@cindex Creating symbols
@cindex Symbols, creating

It is possible to allocate symbols dynamically, this is normally only
necessary when the symbol is to be interned in a non-default obarray or
the symbol is a temporary object which should not be interned (for
example: labels in a compiler).

@defun make-symbol print-name
This function creates and returns a new, uninterned, symbol whose print
name is the string @var{print-name}. Its value cell is void (undefined) 
and it will have an empty property list.

@lisp
(make-symbol "foo")
    @result{} foo
@end lisp
@end defun

@defun gensym
This function returns a new, uninterned, symbol that has a unique print
name.

@lisp
(gensym)
    @result{} G0001

(gensym)
    @result{} G0002
@end lisp
@end defun


@node Interning, Property Lists, Creating Symbols, Symbols
@subsection Interning
@cindex Interning
@cindex Symbols, interning

@dfn{Interning} a symbol means to store it in an obarray so that it can
be found in the future: all variables and named-functions are found
through interned symbols.

When a symbol is interned a hash function is applied to its print name to
determine which bucket in the obarray it should be stored in. Then it is
simply pushed onto the front of that bucket's chain of symbols.

Normally all interning is done automatically by the Lisp reader. When
it encounters the name of a symbol which it can't find in the default
obarray (the value of the variable @code{obarray}) it creates a new
symbol of that name and interns it. This means that no two symbols can
have the same print name, and that the read syntax of a particular
symbol always produces the same object (unless the value of
@code{obarray} is altered).

@lisp
(eq 'some-symbol 'some-symbol)
    @result{} t
@end lisp

@defun intern symbol-name @t{#!optional} obarray
This function uses @code{find-symbol} to search the @var{obarray} (or the
standard obarray) for a symbol called @var{symbol-name}. If a symbol of
that name is found it is returned, otherwise a new symbol of that name is
created, interned into the obarray, and returned.

@lisp
(intern "setq")
    @result{} setq

(intern "my-symbol" my-obarray)
    @result{} my-symbol
@end lisp
@end defun

@defun intern-symbol symbol @t{#!optional} obarray
Interns the symbol @var{symbol} into the obarray @var{obarray} (or the
standard one) then returns the symbol. If @var{symbol} is currently
interned in an obarray an error is signalled.

@lisp
(intern-symbol (make-symbol "foo"))
    @result{} foo

(intern-symbol 'foo)
    @error{} Error: Symbol is already interned, foo
@end lisp
@end defun

@defun unintern symbol @t{#!optional} obarray
This function removes the symbol @var{symbol} from the obarray @var{obarray}
then returns the symbol.

Beware! this function should be used with @emph{extreme} caution---once you
unintern a symbol there may be no way to recover it.

@lisp
(unintern 'setq)                ;This is extremely stupid
    @result{} setq
@end lisp
@end defun


@node Property Lists, Keyword Symbols, Interning, Symbols
@subsection Property Lists
@cindex Property lists
@cindex Symbols, property lists

Each symbol has a property list (or @dfn{plist}), this is a structure which
associates an arbitrary Lisp object with a key (usually a symbol). The
keys in a plist may not have any duplications (so that each property is
only defined once).

The concept of a property list is very similar to an association list
(@pxref{Association Lists}) but there are two main differences:

@enumerate
@item
Structure; each element of an alist represents one key/association pair. In
a plist each pair of elements represents an association: the first
is the key, the second the property. For example, where an alist may
be,

@lisp
((one . 1) (two . 2) (three . 3))
@end lisp

@noindent
a property list would be,

@lisp
(one 1 two 2 three 3)
@end lisp

@item
Plists have their own set of functions to modify the list. This is done
destructively, altering the property list (since the plist is stored in
only one location, the symbol, this is quite safe).
@end enumerate

@defun get symbol property
This function searches the property list of the symbol @var{symbol} for
a property @code{equal} to @var{property}. If such a property is found
it is returned, otherwise false is returned.

@lisp
(get 'if 'lisp-indent)
    @result{} 2

(get 'set 'lisp-indent)
    @result{} ()
@end lisp
@end defun

@defun put symbol property new-value
@code{put} sets the value of the property @var{property} to
@var{new-value} in the property list of the symbol @var{symbol}. If
there is an existing value for this property (using @code{equal} to
compare keys) it is overwritten. The value returned is @var{new-value}.

@lisp
(put 'foo 'prop 200)
    @result{} 200
@end lisp
@end defun

@defun symbol-plist symbol
Returns the property list of the symbol @var{symbol}.

@lisp
(symbol-plist 'if)
    @result{} (lisp-indent 2)
@end lisp
@end defun

@defun setplist symbol plist
This function sets the property list of the symbol @var{symbol} to
@var{plist}.

@lisp
(setplist 'foo '(zombie yes))
    @result{} (zombie yes)
@end lisp
@end defun


@node Keyword Symbols, , Property Lists, Symbols
@subsection Keyword Symbols
@cindex Keyword symbols
@cindex Symbols, keywords

Keywords are a special class of symbols. They evaluate to themselves,
and have the read syntax @samp{#:@var{symbol}}, where @var{symbol} is
anything satisfying the usual symbol syntax. These objects are normally
used to mark keyword parameters in function applications (@pxref{Lambda
Expressions}).

@defun make-keyword symbol
Return the keyword symbol that could be used to mark an argument value
for the keyword parameter @var{symbol}.

@lisp
(make-keyword 'x)
    @result{} #:x
@end lisp
@end defun

@defun keywordp arg
Returns true if @var{arg} is a keyword symbol.
@end defun


@node Evaluation, Variables, Symbols, The language
@section Evaluation
@cindex Evaluation
@cindex Evaluating Lisp forms
@cindex Lisp forms, evaluating

So far only the primitive data types have been discussed, and how the
Lisp reader converts textual descriptions of these types into Lisp
objects. Obviously there has to be a way of actually computing
something---it would be difficult to write a useful program
otherwise.

What sets Lisp apart from other languages is that in Lisp there is no
difference between programs and data: a Lisp program is just a sequence
of Lisp objects which will be evaluated as a program when required.

The subsystem which does this evaluation is called the @dfn{Lisp
evaluator} and each expression to be evaluated is called a @dfn{form}.
The evaluator (the function @code{eval}) examines the structure of the
form that is applied to it and computes the value of that form within
the current Lisp environment.

A form can be any type of data object; the only types which the
evaluator treats specially are symbols (which describe variables) and
lists (subroutine applications), anything else is returned as-is (and
is called a @dfn{self-evaluating form}).

@defun eval form
This function computes and returns the value of @var{form} within the
current module and dynamic environment, and a null lexical environment.
@end defun

However, @code{eval} is rarely explicitly invoked, except in the
read-eval-print loop. Lisp provides many other methods of evaluation
that are usually much more suitable within a program.

@defvar max-lisp-depth
This variable limits the number of nested calls to @code{eval}. If more
than this many nested calls to @code{eval} exist, an error is
signalled. The intention is to detect infinite recursion before hitting
the stack size limit (causing a segmentation fault).
@end defvar

@menu
* Symbol Forms::                How variables are accessed
* List Forms::                  Subroutine calls
* Self-Evaluating Forms::       Forms which don't get evaluated
* Quoting::                     How to prevent evaluation of forms
@end menu


@node Symbol Forms, List Forms, , Evaluation
@subsection Symbol Forms
@cindex Symbol forms
@cindex Forms, symbol
@cindex Forms, variable

When the evaluator is applied to a symbol the computed value of the
form is the value associated with the symbol in the current
environment. Basically this means that to get the value of a variable
you simply write its name. For example,

@lisp
rep-version
    @result{} "1.0"
@end lisp

@noindent
this extract from a Lisp session shows the read syntax of a form to
get the value of the variable @code{rep-version} and the result when
this form is evaluated.

Since forms are evaluated within the current environment the value of a
variable is its most-recent extant binding (with slight differences for
lexical and special variables). @xref{Variables}.

If an evaluated symbol has no current binding, an error is signalled.


@node List Forms, Self-Evaluating Forms, Symbol Forms, Evaluation
@subsection List Forms
@cindex List forms

Forms which are lists are used to invoke a subroutine. The first
element of the list defines the subroutine to be called; all further
elements are arguments to be applied to that subroutine invocation.

There are several different types of subroutines available: functions,
macros, special forms and autoloads. When the evaluator finds a form
which is a list it tries to classify the form into one of these four
types.

First of all it evaluates the first element of the list; the computed
value of this element decides how the rest of the elements in the list
are treated. For example, if the first element is a symbol whose value
is a function, then that function is called with the other values in
the list.

@menu
* Function Call Forms::         `Normal' subroutines
* Macro Call Forms::            Source code expansions
* Special Forms::               Abnormal control structures
* Autoload Forms::              Loading subroutines from files on the fly
@end menu


@node Function Call Forms, Macro Call Forms, , List Forms
@subsubsection Function Call Forms
@cindex Function call forms
@cindex Forms, function call

When the first element of a list form evaluates to a function object
(either a primitive subroutine or a closure), all other elements in the
list are evaluated sequentially from left-to-right, then these values
are applied to the function definition. The result returned by the
function is then taken as the value of the whole list form.

For example, consider the form @code{(/ 100 (1+ 4))}. This is a
function call to the function stored in the variable @code{/}. First
the @code{/} form is evaluated, it is a variable containing a data
value representing the primitive subroutine for integer division. Then
the @code{100} form is evaluated: it is a number, so self-evaluates to
the value @code{100}. Next the form @code{(1+ 4)} is evaluated. This is
also a function call and computes to a value of @code{5} which becomes
the second argument to the @code{/} function. Now the @code{/} function
is applied to its evaluated arguments of @code{100} and @code{5}, and
returns the value @code{20}. This then becomes the value of the form
@code{(/ 100 (1+ 4))}.

@lisp
(/ 100 (1+ 4))
@equiv{} (/ 100 5)
@result{} 20
@end lisp

Or another example,

@lisp
(+ (- 10 (1- 7)) (* (1+ 2) 4)
@equiv{} (+ (- 10 6) (* (1+ 2) 4)
@equiv{} (+ 4 (* (1+ 2) 4)
@equiv{} (+ 4 (* 3 4))
@equiv{} (+ 4 12)
@result{} 16
@end lisp

The system is also capable of eliminating tail calls where possible,
allowing tail-recursive function definitions to run with bounded space
requirements.

A @dfn{tail-call} is a function call that occurs immediately before
exiting the containing function. Since the containing function need not
receive the result of the function call, it is possible to, in effect,
exit from the containing function before invoking the called function.

Note however, that this is only possible where none of the dynamic
features of the language (i.e. bindings to special variables,
@code{unwind-protect}, @code{condition-case}, @code{catch}, etc@dots{})
are currently active in the containing function.

Consider, for example, the following function:

@lisp
(defun print-list (l)
  (unless (null l)
    (format standard-output "%s\n" (car l))
    (print-list (cdr l))))
@end lisp

@noindent
the call to @code{print-list} occurs in the @dfn{tail-position} of the
function. This means that the call may be made after removing the
previous call to @code{print-list} from the interpreter's stack of
active functions.

[ XXX currently the interpreter is incapable of eliminating tail calls
to subrs, i.e. Lisp functions implemented in C ]


@node Macro Call Forms, Special Forms, Function Call Forms, List Forms
@subsubsection Macro Call Forms
@cindex Macro call forms
@cindex Forms, macro call

Macros are source code expansions, the general idea is that a macro
is a function which using the unevaluated arguments applied to it,
computes another form (the expansion of the macro and its arguments)
which is then evaluated to provide the value of the form.

Macros are generally used to implement control-flow operations, where
not all arguments may be evaluated, or evaluated in an unusual order.
For more details see @ref{Macros}.


@node Special Forms, Autoload Forms, Macro Call Forms, List Forms
@subsubsection Special Forms
@cindex Special forms
@cindex Forms, special

Special forms are built-in subroutines which the evaluator knows must
be handled specially. The main difference between a special form and a
function is that the arguments applied to a special form are @emph{not}
automatically evaluated---if necessary the special form will evaluate
arguments itself. This will be noted in the documentation of the
special form.

Special forms are generally used to provide control structures, for
example, the primitive conditional constructs are special forms (if all
of their arguments, including the forms to be conditionally evaluated,
were evaluated automatically this would defeat the object of being
conditional!).

The special forms supported by @code{librep} are: @code{cond},
@code{defvar}, @code{progn}, @code{quote}, @code{setq}.

@defun special-form-p arg
Returns true if @var{arg} is a special form.

@lisp
(special-form-p quote)
    @result{} t
@end lisp
@end defun


@node Autoload Forms, , Special Forms, List Forms
@subsubsection Autoload Forms
@cindex Autoload forms
@cindex Forms, autoload

Not all parts of @code{librep} are needed at once, autoload forms
provide a means of marking that a function (or macro) is contained by a
specific Lisp library. The first time that the function is accessed the
autoload form will be evaluated; this loads the file containing the
function, then re-evaluates the original form. By then the autoload
form will have been overwritten in the symbol's function slot by the
true function (when it was loaded) so the form will execute properly.

For more details see @ref{Autoloading}.


@node Self-Evaluating Forms, Quoting, List Forms, Evaluation
@subsection Self-Evaluating Forms
@cindex Self-evaluating forms
@cindex Forms, self-evaluating
@cindex Forms, constant

The computed value of any form which is not a symbol or a list will
simply be the form itself and the form is said to be a @dfn{self-evaluating
form}.

Usually the only forms to be evaluated in this way will be numbers, strings
and vectors (since they are the only other data types which have read
syntaxes) but the effect is the same for other types of data.

This means that forms you know are self-evaluating do not have to be
quoted to be used as constants (like lists and symbols do).

@lisp
"foo"
    @result{} "foo"
@end lisp

@node Quoting, , Self-Evaluating Forms, Evaluation
@subsection Quoting
@cindex Quoting

As the above sections explain some types of Lisp object have special
meaning to the Lisp evaluator (namely the symbol and list types) this
means that if you want to refer to a symbol or a list in a program you
can't because the evaluator will treat the form as either a variable
reference or a function call respectively.

To get around this Lisp uses an idea called @dfn{quoting}. The special
form @code{quote} simply returns its argument without evaluating it.
For example,

@lisp
(quote my-symbol)
    @result{} my-symbol
@end lisp

@noindent
the @code{quote} form prevents the @code{my-symbol} being treated as a
variable---it is effectively `hidden' from the evaluator.

Writing @samp{quote} all the time would be a bit time-consuming so
there is a shortcut: the Lisp reader treats any form @var{x} preceded
by a single quote character (@samp{'}) as the form @code{(quote
@var{x})}. So the example above would normally be written as,

@lisp
'my-symbol
    @result{} my-symbol
@end lisp

The general way to prevent evaluation of a form is to simply precede it
by a single quote-mark.

@defspec quote form
This special form returns its single argument without evaluating it. This
is used to @dfn{quote} constant objects to prevent them from being
evaluated.
@end defspec

For another form of quoting, see @ref{Backquoting}.


@node Variables, Functions, Evaluation, The language
@section Variables
@cindex Variables

In Lisp, symbols are used to represent variables. Each symbol contains
a @dfn{value} slot that is used to contain the value of the symbol when
it used as a variable.

The normal way to obtain the current value of a variable is simply to
evaluate the symbol of the same name (i.e. write the name of the
variable in your program). The @code{symbol-value} function can be used
to evaluate variables whose names not known statically.

@defun symbol-value variable
This function returns the value of the symbol @var{variable} in
the current environment.
@end defun

@menu
* Local Variables::             Creating temporary variables
* Setting Variables::           Altering a variable's value
* Scope and Extent::            Technical jargon
* Void Variables::              Some variables have no values
* Defining Variables::          How to define a variable before
                                  using it
* Fluid Variables::             Another dynamic bindingd methodb
@end menu


@node Local Variables, Setting Variables, , Variables
@subsection Local Variables
@cindex Local variables
@cindex Variables, local

A @dfn{local variable} is a variable which has a temporary value. For
example, when a function is called the variables which are the names of
its arguments are temporarily bound to the values of the arguments
passed to the function. When the function call exits its arguments are
unbound and the previous definitions of the variables come back into
view.

A @dfn{binding} is a particular instance of a local variable. Even if a
variable has more than one binding currently in place, only the most
recent is available---there is no way the previous binding can be
accessed until the previous binding is removed.

One way of visualising variable binding is to think of each variable as
a stack. When the variable is bound to, a new value is pushed onto the
stack, when it is unbound the top of the stack is popped. Similarly
when the stack is empty the value of the variable is void (@pxref{Void
Variables}). Assigning a value to the variable (@pxref{Setting
Variables}) overwrites the top value on the stack with a new value.
When the value of the variable is required it is simply read from the
top of the stack.

Apart from function applications there are two special forms which
perform variable binding (i.e. creating local variables), @code{let}
and @code{let*}.

@defmac let bindings body-forms@dots{}
@code{let} creates new variable bindings as specified by the
@var{bindings} argument, then evaluates the @var{body-forms} in order.
The bindings are then removed, returning all variables to their state
before the @code{let} statement was entered. The value of the statement
is the value of the implicit @code{progn}.

The @var{bindings} argument is a list of the bindings to perform. Each
binding is either a symbol, in which case that variable is bound to
@code{()}, or a list whose car is a symbol. The cdr of this list is a
list of forms which, when evaluated as a @code{progn}, gives the value
to bind to that variable.

@lisp
(setq foo 42)
    @result{} 42
(let
    ((foo (+ 1 2))
     bar)
  ;; Body forms
  (setq foo (1+ foo))   ;This sets the new binding
  (cons foo bar))
    @result{} (4 . ())
foo
    @result{} 42        ;The original values is back
@end lisp

No bindings are made until all new values have been computed. For
example:

@lisp
(setq foo 42)
    @result{} 42
(let
    ((foo 100)
     (bar foo))
  (cons foo bar))
    @result{} (100 . 42)
@end lisp

@noindent
Although @code{foo} is given a new binding this is not actually done
until all the new values have been computed, hence @code{bar} is
bound to the @emph{old} value of @code{foo}. 
@end defmac

@defmac let* bindings body-forms@dots{}
This special form is exactly the same as @code{let} except for one
important difference: the new bindings are installed @emph{as they are
computed}.

You can see the difference by comparing the following example with the
last example in the @code{let} documentation (above),

@lisp
(setq foo 42)
    @result{} 42
(let*                   ;Using @code{let*} this time
    ((foo 100)
     (bar foo))
  (cons foo bar))
    @result{} (100 . 100)
@end lisp

@noindent
By the time the new value of @code{bar} is computed the new binding of
@code{foo} is already active.
@end defmac

@defmac letrec bindings body-forms@dots{}
@code{letrec} is similar to @code{let} and @code{let*}, with the
differerence being that the values of bindings are evaluated with all
other bindings in scope. This means that recursive functions may be
defined with @code{letrec}. For example, a local factorial function
(from SICP):

@lisp
(letrec ((fact
          (lambda (n)
            (if (= n 1)
                1
              (* n (fact (1- n)))))))
  (fact 10))
@end lisp

@noindent
Note also that letrec allows groups of mutually recursive functions to
be defined, as in the following example (also from SICP):

@lisp
(defun f (x)
  (letrec ((evenp
            (lambda (n)
              (if (= n 0)
                  t
                (oddp (1- n)))))
           (oddp
            (lambda (n)
              (if (= n 0)
                  nil
                (evenp (1- n))))))
    @dots{}
@end lisp
@end defmac


@node Setting Variables, Scope and Extent, Local Variables, Variables
@subsection Setting Variables
@cindex Setting variables
@cindex Variables, setting

@dfn{Setting} a variable means to overwrite its current value (that is,
the value of its most recent active binding) with a new one. In the
variable-as-stack analogy, this is analogous to overwriting the top of
the stack. The old value is irretrievably lost (unlike when a new value
is bound to a variable, @pxref{Local Variables}).

The @code{setq} special form is the usual method of altering the value
of a variable.

@defspec setq variable form @dots{}
Each @var{variable} is set to the result of evaluating its
corresponding @var{form}. The last value assigned becomes the value of
the @code{setq} form.

@lisp
(setq x 20 y (+ 2 3))
    @result{} 5
@end lisp

@noindent
In the above example the variable @code{x} is set to @code{20} and @code{y}
is set to the value of the form @code{(+ 2 3)} (5).
@end defspec

@defun set variable new-value
The value of the variable @var{variable} (a symbol) is set to
@var{new-value} and the @var{new-value} is returned.

This function is used when the @var{variable} is unknown until
run-time, and therefore has to be computed from a form.

@lisp
(set 'foo 20)
@equiv{}
(setq foo 20)           ;@code{setq} means `set-quoted'
    @result{} 20
@end lisp

@emph{Note:} currently the @code{set} function may be used to set any
type of variable (i.e. lexical or special). However this likely to
change in the future, such that only special variables will be allowed
to be modified using the @code{set} function. It is strongly advised to
avoid using this function on lexical bindings! (Moreover the compiler
may generate incorrect code in certain circumstances.)
@end defun


@node Scope and Extent, Void Variables, Setting Variables, Variables
@subsection Scope and Extent
@cindex Scope and extent
@cindex Variables, scope and extent of

In the @code{librep} dialect of Lisp by default variables have
@dfn{lexical scope}. This means that bindings are associated with
textual regions of programs, and may be accessed by any forms within
this associated textual region. Moreover, the bindings are persistent,
even when the flow of control is currently outside the associated
region.

Consider the following example:

@lisp
(let
    ((counter 0))
  (defun count ()
    (setq counter (1+ counter))
    counter))
@end lisp

@noindent
the value of the @code{counter} variable persists, and is incremented
each time the @code{count} function is called. The @code{counter}
variable is accessible from nowhere but the forms written inside the
@code{let} statement declaring it.

@lisp
(count)
  @result{} 1
(count)
  @result{} 2
@end lisp

An alternative method of scoping variables is also available. Any
variables declared using the @code{defvar} special form are said to be
@dfn{special} variables, they have @dfn{indefinite scope} and
@dfn{dynamic extent}, often simplified to @dfn{dynamic scope}. What
this means is that references to these variables may occur anywhere in
a program (i.e. bindings established in one function are visible within
functions called from the original function) and that references may
occur at any point in time between the binding being created and it
being unbound.

Dynamic scoping is easy to abuse, making programs hard to understand
and debug. A quick example of the use of dynamic scope,

@lisp
(defvar *foo-var* nil)

(defun foo (x)
  (let
      ;; a dynamically-scoped binding
      ((*foo-var* (* x 20)))
    (bar x)
    @dots{}

(defun bar (y)
  ;; Since this function is called from
  ;; the function @code{foo} it can refer
  ;; to @code{*foo-var*}
  (setq y (+ y *foo-var*))
  @dots{}
@end lisp

@noindent
As shown in the previous example, a common convention is to mark
special variables by enclosing their names within asterisks.


@node Void Variables, Defining Variables, Scope and Extent, Variables
@subsection Void Variables
@cindex Void variables
@cindex Variables, void

A variable which has no value is said to be @dfn{void}, attempting to
reference the value of such a symbol will result in an error. It is
possible for the most recent binding of a variable to be void even though
the inactive bindings may have values.

@defun boundp variable
Returns true if the symbol @var{variable} has a value.
@end defun

@defun makunbound variable
This function makes the current binding of the symbol @var{variable} be
void, then returns @var{variable}.

@lisp
(setq foo 42)
    @result{} 42
foo
    @result{} 42
(boundp 'foo)
    @result{} t
(makunbound 'foo)
    @result{} foo
(boundp 'foo)
    @result{} ()
foo
    @error{} Value as variable is void: foo
@end lisp
@end defun


@node Defining Variables, Fluid Variables, Void Variables, Variables
@subsection Defining Variables
@cindex Defining variables
@cindex Variables, defining

The special forms @code{define}, @code{defvar} and @code{defconst}
allow you to define the global variables that will be used by a
program.

@defmac define variable form
Defines a lexically scoped global variable called @var{variable}. It
will have the result of evaluating @var{form} assigned to it.

Note that the @code{define} special form may also be used to declare
block-structured functions, @ref{Definitions}.
@end defmac

@defspec defvar variable [form [doc-string]]
This special form defines a special (i.e. dynamically scoped) variable,
the symbol @var{variable}. If the value of @var{variable} is void the
@var{form} is evaluated and its value is stored as the value of
@var{variable} (note that only the default value is modified, never a
buffer-local value). If no @var{form} is given the assigned value
defaults to false.

If the @var{doc-string} argument is defined it is a string documenting
@var{variable}. This string is then stored as the symbol's
@code{variable-documentation} property and can be accessed by the
@code{describe-variable} function.

@lisp
(defvar *my-variable* '(x y)
  "This variable is an example showing the usage of the @code{defvar}
special form.")
    @result{} *my-variable*
@end lisp
@end defspec

@defmac defconst constant form [doc-string]
@code{defconst} defines a global constant, the symbol @var{constant}.
Its value is set to the result of evaluating @var{form}. Note that
unlike @code{defvar} the value of the symbol is @emph{always} set, even
if it already has a value.

The @var{doc-string} argument, if defined, is the documentation string
for the constant.

@lisp
(defconst the-answer 42
  "An example constant.")
    @result{} the-answer
@end lisp
@end defmac


@node Fluid Variables, , Defining Variables, Variables
@subsection Fluid Variables
@cindex Fluid variables
@cindex Variables, fluid

Special variables have a number of drawbacks, especially when used in
conjunction with the module system (@pxref{Modules and Special
Variables}). As a consequence of these drawbacks, @code{rep} provides a
second method of implementing dynamically scoped variables, known as
@dfn{fluid variables}, or just @dfn{fluids}.

A fluid is a first class Lisp object that may be passed around like any
other Lisp object. Its sole function is to provide a location from
which dynamic bindings may be created. Fluids are anonymous objects,
they are usually named by being stored in lexically scoped variables.

@defun make-fluid @t{#!optional} value
Create and return a new fluid, it will have an initial binding of
@var{value} (or false if @var{value} is undefined).
@end defun

@defun fluid fluid
Return the value of the most recently created binding of the fluid
variable object @var{fluid}.
@end defun

@defun fluid-set fluid value
Set the value of the most recently created binding of the fluid
variable object @var{fluid} to @var{value}.
@end defun

@defun with-fluids fluids values thunk
Call the zero parameter function @var{thunk} (and return the value that
it returns) with new bindings created for each of the fluid variables
specified in the list @var{fluids}. 

For each member of @var{fluids} the corresponding member of the
@var{values} list provides the initial value of the new binding.

If the lists @var{fluids} and @var{values} are not of the same length,
an error is signalled.
@end defun

@defmac let-fluids bindings body @dots{}
A convenient wrapper around @code{with-fluids}, similar to the
@code{let} syntax.

The list @var{bindings} associates the names of lexical variables
containing fluid objects, with the values to bind to those fluid
objects. Once the bindings have been installed, the @var{body @dots{}}
forms are evaluated, and the bindings removed. The value of the last of
the @var{body @dots{}} forms is returned.
@end defmac

Here is an example code fragment using fluid variables and
@code{let-fluids}:

@lisp
(define a (make-fluid))
(define b (make-fluid))

(let-fluids ((a 1)
             (b 2))
  (+ (fluid a) (fluid b))) @result{} 3
@end lisp


@node Functions, Macros, Variables, The language
@section Functions
@cindex Functions

A @dfn{function} is a Lisp object which, when applied to a sequence of
argument values, produces another value---the function's
@dfn{result}. It may also induce side-effects (e.g. changing the
environment of the calling function). All Lisp functions return results
--- there is nothing like a procedure in Pascal.

Note that special forms (@pxref{Special Forms}) and macros
(@pxref{Macros}) are @emph{not} functions since they do not guarantee
to evaluate all of their arguments.

Functions are the main building-block in Lisp programs, each program is
usually a system of interrelated functions.

There are two types of function: @dfn{primitive functions} are
functions written in the C language, these are sometimes called
built-in functions, the object containing the C code itself is called a
@dfn{subr}. All other functions are defined in Lisp.

@defun functionp object
Returns true if @var{object} is a function (i.e. it can be used
as the function argument of @code{funcall}.

@lisp
(functionp set)
    @result{} t

(functionp setq)
    @result{} ()

(functionp (lambda (x) (+ x 2)))
   @result{} t
@end lisp
@end defun

@defun subrp arg
Returns true is @var{arg} is a primitive subroutine object.
@end defun

@defun subr-name subr
Returns a string naming the primitive subroutine @var{subr}.
@end defun

@menu
* Lambda Expressions::          Structure of a function object
* Defining Functions::          How to write a function definition
* Anonymous Functions::         Or they can be un-named
* Predicate Functions::         Functions which return boolean values
* Local Functions::             Binding functions temporarily
* Calling Functions::           Functions can be called by hand
* Mapping Functions::           Map a function to the elements of a list
@end menu


@node Lambda Expressions, Defining Functions, , Functions
@subsection Lambda Expressions
@cindex Lambda expressions
@cindex Functions, lambda expressions

@dfn{Lambda expressions} are used to create functions from other Lisp
objects. A lambda expression is a list whose first element is the
symbol @code{lambda}. All functions written in Lisp (as opposed to the
primitive functions in C) are defined using lambda expressions.

The general format of a lambda expression is:

@lisp
(lambda @var{lambda-list} [@var{doc}] [@var{interactive-declaration}] @var{body-forms}@dots{} )
@end lisp

@noindent
Where @var{lambda-list} is a list defining the formal parameters of the
function, @var{doc} is an optional documentation string,
@var{interactive-declaration} is only required by interactive commands 
@footnote{Only used when @code{librep} is embedded within another
application.} and @var{body-forms} is the sequence of forms making up
the function body, evaluated using an implicit @code{progn}.

The @var{lambda-list} is a list, it defines how the values applied to
the function are bound to local variables which represent the
parameters of the function. At its simplest it is simply a list of
symbols, each symbol will have the corresponding argument value bound
to it. For example, the lambda list @code{(x y)} defines two
parameters, @code{x} and @code{y}. When called with two arguments the
first will be bound to the variable @code{x}, the second to @code{y}.
When used in a full lambda expression this looks like:

@lisp
(lambda (x y) (+ x y))
@end lisp

@noindent
this evaluates to an anonymous function with two parameters, @code{x}
and @code{y}, which when called evaluates to their sum.

Note that a lambda expression itself is @emph{not} a function, it must
be associated with a lexical environment, this conjunction is usually
called a closure; it is the closure that may be called as a function.

However, to confuse matters, a lambda expression @emph{evaluates} to
the closure of itself and the current environment. Consider the
following example:

@lisp
(lambda (x) (1+ x))
    @result{} #<closure>

(functionp (lambda (x) (1+ x)))
    @result{} t

(functionp '(lambda (x) (1+ x)))
    @result{} ()
@end lisp

There are several @dfn{lambda-list keywords} which modify the meaning
of symbols in the lambda-list. The syntax of the lambda list is:

@lisp
([@var{required-parameters}@dots{}]
 [#!optional @var{optional-parameters}@dots{}]
 [#!key @var{keyword-parameters}@dots{}]
 [#!rest @var{rest-parameter} | . @var{rest-parameter}])
@end lisp

@noindent
Each lambda list keyword is a symbol whose name begins @samp{#!}, they
are interpreted as follows:

@table @code
@item #!optional
All variables following this keyword are considered @dfn{optional} (all
variables before the first keyword are @dfn{required}: an error will be
signalled if a required argument is undefined in a function call).

@var{optional-parameters} may either be of the form @code{@var{symbol}}
or of the form @code{(@var{symbol} @var{default})}. If no argument is
supplied for this parameter the @var{default} form is evaluated to give
the bound value@footnote{The @var{default} form is evaluated in the
environment of the closure being called, but without any of the
bindings created by the lambda expression.}. If no @var{default} form
is given, then the variable is bound to a false value.

Note that optional parameters must be specified if a later parameter is
also specified.

@lisp
((lambda (#!optional a b) (list a b)))
    @result{} (() ())
((lambda (#!optional a b) (list a b)) 1)
    @result{} (1 ())
((lambda (#!optional a b) (list a b)) nil 1)
    @result{} (() 1)
((lambda (#!optional (a 1)) (list a)))
    @result{} (1)
((lambda (#!optional (a 1)) (list a)) 2)
    @result{} (2)
@end lisp

@item #!key
This object marks that the parameters up to the next lambda list
keyword are keyword parameters. The values bound to these parameters
when the function is called are determined not by position (as with
normal parameters), but by being marked by a preceding keyword symbol.
Keyword symbols have the syntax @samp{#:@var{symbol}}.

As with optional parameters, default values may be supplied through the
use of the @code{(@var{symbol} @var{default})} syntax. If no default
value is given and no keyword argument of the specified kind is
available, the variable is bound to a false value.

For example, the lambda list @code{(a #!key b c)} accepts one required
argument, and two optional keyword arguments. The variable @code{a}
would be bound to the first supplied argument; the variable @code{b}
would be bound to the argument preceded by the keyword @code{#:b}, or
@code{()} if no such argument exists. (After extracting required and
optional arguments, each remaining pair of values is checked for
associating a value with each keyword.)

@lisp
((lambda (a #!key b c) (list a b c)) 1 2 3)
    @result{} (1 () ())
((lambda (a #!key b c) (list a b c)) 1 #:b 2 3)
    @result{} (1 2 ())
((lambda (a #!key b c) (list a b c)) 1 #:b 2 #:c 3)
    @result{} (1 2 3)
((lambda (a #!key b c) (list a b c)) 1 #:c 3 #:b 2)
    @result{} (1 2 3)
@end lisp

@item #!rest
The @code{#!rest} keyword allows a variable number of arguments to be
applied to a function, all the argument values which have not been
bound to argument variables (or used to mark keyword arguments) are
made into a list and bound to the variable following the @code{#!rest}
keyword. For example, in

@lisp
(lambda (x #!rest y) @dots{})
@end lisp

@noindent
the first argument, @code{x}, is required. Any other arguments applied
to this function are made into a list and this list is bound to the
variable @code{y}.

Variable argument functions may also be defined through the Scheme
method of using an improper lambda-list. The previous example is
exactly equivalent to:

@lisp
(lambda (x . y) @dots{})
@end lisp
@end table

When a function represented by a lambda-list is called the first action
is to bind the argument values to the formal parameters. The
@var{lambda-list} and the list of argument values applied to the
function are worked through in parallel. Any required arguments which
are left undefined when the end of the argument values has been reached
causes an error.

After the arguments have been processed the @var{body-forms} are
evaluated by an implicit progn, the value of which becomes the value of
the function call. Finally, all parameters are unbound and control
passes back to the caller.


@node Defining Functions, Anonymous Functions, Lambda Expressions, Functions
@subsection Defining Functions
@cindex Defining functions
@cindex Functions, defining

Globally accessible functions are usually defined by the @code{defun}
special form.

@defmac defun name lambda-list body-forms@dots{}
@code{defun} initialises the function definition of the symbol
@var{name} to the lambda expression resulting from the concatenation of
the symbol @code{lambda}, @var{lambda-list} and the @var{body-forms}.

The @var{body-forms} may contain a documentation string for the
function as its first form and an interactive calling specification as
its first (if there is no doc-string) or second form if the function
may be called interactively by the user (@pxref{Lambda Expressions}).
@end defmac

An example function definition taken from the @code{librep} source code is:

@lisp
(defun load-all (file)
  "Try to load files called FILE (or FILE.jl, etc) from all
directories in the Lisp load path."
  (mapc (lambda (dir)
          (let
              ((full-name (expand-file-name file dir)))
            (when (or (file-exists-p full-name)
                      (file-exists-p (concat full-name ".jl"))
                      (file-exists-p (concat full-name ".jlc")))
              (load full-name nil t))))
        load-path))
@end lisp


@node Anonymous Functions, Predicate Functions, Defining Functions, Functions
@subsection Anonymous Functions
@cindex Anonymous functions
@cindex Functions, anonymous

When supplying functions as arguments to other functions it is often
useful to give an actual function @emph{definition} (i.e. an enclosed
lambda expression) instead of the name of a function.

In Lisp, unlike most other programming languages, functions have no
inherent name. As seen in the last section named-functions are created
by storing a function object in a variable, if you want, a function can
have many different names: simply store the function in many different
variables!

So, when you want to pass a function as an argument there is the option
of just writing down its definition. This is especially useful with
functions like @code{mapc} and @code{delete-if}. For example, the
following form removes all elements from the @var{list} which are even
and greater than 20.

@lisp
(setq @var{list} (delete-if (lambda (x)
                        (and (zerop (% x 2)) (> x 20)))
                      @var{list}))
@end lisp

The above lambda expression combines two predicates applied to its
argument.

In certain cases it may be necessary to create a non-constant function,
for example by using backquoting (@pxref{Backquoting}). In these cases
the @code{make-closure} function may be used to create a function
object from a lambda expression.

@defun make-closure arg
Return the closure of @var{arg} and the current lexical environment.
@end defun

@defun closurep arg
Returns true if @var{arg} is a closure.
@end defun

@defun closure-function closure
Returns the function object associated with the lexical closure
@var{closure}.
@end defun


@node Predicate Functions, Local Functions, Anonymous Functions, Functions
@subsection Predicate Functions
@cindex Predicate functions
@cindex Boolean values, predicate functions

In Lisp, a function which returns a boolean `true' or boolean `false'
value is called a @dfn{predicate}. As is the convention in Lisp a value
of @code{()} means false, anything else means true. The symbols
@code{nil} and @code{t} are often used to represent constant false and
true values (@pxref{nil and t}).

Another Lisp convention is that the names of predicate functions should
name the quality that the predicate is testing followed by either a
@samp{p} or @samp{-p} string. The @samp{p} variant is used when the
first string does not contain any hyphens.

For example, the predicate to test for the quality @dfn{const-variable}
(a variable which has a constant value, @pxref{Defining Variables}) is
called @code{const-variable-p}. On the other hand the predicate to test
for the quality @dfn{cons} (a Cons cell) is called @code{consp}.


@node Local Functions, Calling Functions, Predicate Functions, Functions
@subsection Local Functions
@cindex Local functions
@cindex Functions, local

The @code{defun} special form allows globally-accessible functions to
be defined. It is often desirable to declare functions local to the
current lexical environment. The @code{let} and @code{let*} special
form that were introduced earlier allow this since named functions are
simply functional values stored in variables.

For example,

@lisp
(let
    ((temporary-function (lambda (x)
                           (+ x 42))))
  @dots{}
  (temporary-function 20)
  @dots{}
@end lisp


@node Calling Functions, Mapping Functions, Local Functions, Functions
@subsection Calling Functions
@cindex Calling functions
@cindex Functions, calling

Most of the time function applications are made by the evaluator when
it finds a functional value after evaluating the first element of a
list form. However two functions are available for manually calling
functions.

@defun funcall function @t{#!rest} args
Applies the argument values @var{args} to the function @var{function}, then
returns its result.
@end defun

@defun apply function @t{#!rest} args
Similar to @code{funcall} except that the last of its arguments is
a @emph{list} of arguments which are appended to the other members of
@var{args} to form the list of argument values to apply to the
function @var{function}.

@lisp
(apply + 1 '(2 3))
    @result{} 6

(apply + (make-list 1000000 1))
    @result{} 1000000
@end lisp
@end defun


@node Mapping Functions, , Calling Functions, Functions
@subsection Mapping Functions
@cindex Mapping functions
@cindex Functions, mapping
@cindex Lists, mapping

A @dfn{mapping function} applies a function to each of a collection of
objects. @code{librep} currently has two mapping functions,
@code{mapcar} and @code{mapc}.

@defun mapcar function list
Each element of @var{list} is individually applied to the function
@var{function}. The values returned are made into a new list which is
returned.

The @var{function} must accept a single argument value.

@lisp
(mapcar 1+ '(1 2 3 4 5))
    @result{} (2 3 4 5 6)
@end lisp
@end defun

@defun mapc function list
Similar to @code{mapcar} except that the values returned when each
element is applied to the function @var{function} are discarded. The
value returned is undefined.

This function is generally used where the side effects of calling the
function are the important thing, not the results. It is often the most
efficient way of traversing all items in a list, for example:

@lisp
(mapc (lambda (x)
        (print x standard-error)) list)
@end lisp
@end defun

The two following functions are also mapping functions of a sort. They
are variants of the @code{delete} function (@pxref{Modifying Lists})
and use predicate functions to classify the elements of the list which
are to be deleted.

@defun delete-if predicate list
This function is a variant of the @code{delete} function. Instead of
comparing each element of @var{list} with a specified object, each
element of @var{list} is applied to the predicate function
@var{predicate}. If it returns true then the
element is destructively removed from @var{list}.

@lisp
(delete-if stringp '(1 "foo" 2 "bar" 3 "baz"))
    @result{} (1 2 3)
@end lisp
@end defun

@defun delete-if-not predicate list
This function does the inverse of @code{delete-if}. It applies
@var{predicate} to each element of @var{list}, if it returns false
then the element is destructively removed from the list.

@lisp
(delete-if-not stringp '(1 "foo" 2 "bar" 3 "baz"))
    @result{} ("foo" "bar" "baz")
@end lisp
@end defun

The @code{filter} function is similar to @code{delete-if-not}, except
that the original list isn't modified, a new list is created.

@defun filter predicate list
Return a new list, consisting of the elements in @var{list} which the
function @var{predicate} returns true when applied to. This
function is equivalent to:

@lisp
(mapcar nconc (mapcar (lambda (x)
                        (and (@var{predicate} x) (list x)))
                      @var{list}))
@end lisp
@end defun


@node Macros, Definitions, Functions, The language
@section Macros
@cindex Macros

@dfn{Macros} are used to extend the Lisp language. They consist of a
function which instead of returning a computed value, transform their
unevaluated arguments into a new form that, when evaluated, produces
the actual value of the original form.

For example, the @code{when} macro (@pxref{Conditional Structures})
implements a new conditional operation by transforming its arguments
into a @code{cond} statement. That is,

@lisp
(when @var{condition} @var{form} @dots{})
    @expansion{} (cond (@var{condition} @var{form} @dots{}))
@end lisp

Since macros do not evaluate their arguments, instead just transforming
them, they may be expanded at @emph{compile-time}. The resulting form
is then compiled as usual.

@defun macrop arg
Returns true if @var{arg} is a macro object.
@end defun

@menu
* Defining Macros::             Macros are defined like functions
* Backquoting::                 Creating macros from templates
* Macro Expansion::             How macros are used by the evaluator
* Compiling Macros::            The compiler expands macros at compile-
                                  time.
@end menu


@node Defining Macros, Backquoting, , Macros
@subsection Defining Macros
@cindex Defining macros
@cindex Macros, defining

Macros are defined in the same style as functions, the only difference
is the name of the special form used to define them.

A macro object is a list whose car is the symbol @code{macro}, its
cdr is the function which creates the expansion of the macro when
applied to the macro calls unevaluated arguments.

@defmac defmacro name lambda-list body-forms@dots{}
Defines the macro stored in the function cell of the symbol @var{name}.
@var{lambda-list} is the lambda-list specifying the arguments to the
macro (@pxref{Lambda Expressions}) and @var{body-forms} are the forms
evaluated when the macro is expanded. The first of @var{body-forms}
may be a documentation string describing the macro's use.
@end defmac

Here is a simple macro definition, it is the definition of the
@code{when} macro shown in the previous section.

@lisp
(defmacro when (condition #!rest body)
  "Evaluates @var{condition}, if it's true evaluates the @var{body}
forms."
  (list 'cond (list* condition body)))
@end lisp

@noindent
When a form of the type @code{(when @var{c} @var{b} @dots{})} is
evaluated the macro definition of @code{when} expands to the form
@code{(cond (@var{c} (progn @var{b} @dots{})))} which is then evaluated
to perform the @code{when}-construct.

When you define a macro ensure that the forms which produce the
expansion have no side effects; otherwise undefined effects will occur
when programs using the macro are compiled.


@node Backquoting, Macro Expansion, Defining Macros, Macros
@subsection Backquoting
@cindex Backquoting
@cindex Macros, backquoting

As seen in the previous sections, macros are a very powerful mechanism
of defining new control structures. However due to the need to create
the expansion, i.e. the form that will be actually evaluated, they can
often be complex to write and understand.

We have already seen that constants may be produced through the use of
the quote-mark (@pxref{Quoting}), here another form of quoting is
described, where only some of the quoted object is actually constant.
This is known as @dfn{backquoting}, since it is introduced by the
backquote character @samp{`}, a shortcut for the @code{backquote}
macro.

@defmac backquote arg
Constructs a new version of @var{arg} (a list). All parts of @var{list}
are preserved except for expressions introduced by comma (@samp{,})
characters, which are evaluated and spliced into the list. For example:

@lisp
`(1 2 ,(+ 1 2))
    @result{} (1 2 3)
@end lisp

Also, the @samp{,@@} prefix will splice the following @emph{list} into
the output list, at the same level:

@lisp
`(1 2 ,@@(list 3))
    @result{} (1 2 3)
@end lisp
@end defmac

Backquoting allows macros expansions to be created from static
templates. For example the @code{when} macro shown in the previous
sections can be rewritten as:

@lisp
(defmacro when (condition #!rest body)
  `(cond (,condition ,@@body)))
@end lisp

@noindent
which is easier to read, since it is a lot closer to the actual
expansion.


@node Macro Expansion, Compiling Macros, Backquoting, Macros
@subsection Macro Expansion
@cindex Macro expansion
@cindex Expansion, of macros

When a macro call is detected (@pxref{List Forms}) the function which
is the cdr of the macro's definition (@pxref{Defining Macros}) is
applied to the macro call's arguments. Unlike in a function call, the
arguments are @emph{not evaluated}, the actual forms are the arguments
to the macro's expansion function. This is to allow these forms to be
rearranged by the macro's expansion function, creating the form that
will finally be evaluated.

There is a function which performs macro expansion, its main use is to
let the Lisp compiler expand macro calls at compile time.

@defun macroexpand form @t{#!optional} environment
If @var{form} is a macro call @code{macroexpand} will expand that call
by calling the macro's expansion function (the cdr of the macro definition).
If this expansion is another macro call the process is repeated until
an expansion is obtained which is not a macro call, this form is
then returned.

The optional @var{environment} argument is a function to call to do the
actual expansion.

@lisp
(defmacro when (condition #!rest body)
  "Evaluates @var{condition}, if it's true evaluates the @var{body}
forms."
  (list 'if condition (cons 'progn body)))
    @result{} when

(macroexpand '(when x (setq foo bar)))
    @result{} (cond (x (progn (setq foo bar))))
@end lisp

While a macro is being expanded, the special variable
@code{macro-environment} is bound to value of the @var{environment}
parameter in the containing call to @code{macroexpand}. This allows
macros to expand inner macros correctly.
@end defun

@defun macroexpand-1 form @t{#!optional} environment
Similar to @code{macroexpand}, but only a single macro expansion is
ever performed, i.e. if @var{form} is a macro call the result of
expanding that call will be returned, otherwise @var{form} is returned.

@lisp
(macroexpand-1 '(when x (setq foo bar)))
    @result{} (if x (progn (setq foo bar)))
@end lisp
@end defun


@node Compiling Macros, , Macro Expansion, Macros
@subsection Compiling Macros
@cindex Compiling macros
@cindex Macros, compiling

Although it may seem odd that macros return a form to produce a result
and not simply the result itself, this is actually their most important
feature. It allows the expansion and the evaluation of the expansion to
occur at different times.

The Lisp compiler makes use of this; when it comes across a macro call
in a form it is compiling it uses the @code{macroexpand} function to
produce the expansion of that form. This expansion is then compiled
straight into the object code. Obviously this is good for performance
(why evaluate the expansion every time it is needed when once will
do?).

Some rules do need to be observed to make this work properly:

@itemize @bullet
@item
The macro expansion function (i.e. the definition of the macro) should
not have any side effects or evaluate its arguments (the value of a symbol
at compile-time probably won't be the same as its value at run-time).

@item
Macros which are defined by another file must be loaded so they can be
recognised. Use the @code{require} function, the compiler will evaluate
any @code{require} forms it sees loading any macro definitions used.
@end itemize

Note however, that the @code{librep} compiler does allow macros to be
used before they are defined (two passes are made through the source
file).


@node Definitions, Modules, Macros, The language
@section Block-Structured Definitions
@cindex Block structured definitions
@cindex Definitions, block structured
@cindex Functions, block structured

Previous sections of this document have described several special forms
and macros for defining top-level functions and variables.
@code{librep} also provides a higher-level method of creating these
definitions, the @code{define} statement. @code{define} originates in
the Scheme dialect of Lisp, it allows block-structured programs to be
defined intuitively.

The most basic use of @code{define} is very similar to @code{defun},
e.g. the two following forms have exactly the same effect:

@lisp
(defun foo (x) (1+ x))

(define (foo x) (1+ x))
@end lisp

@noindent
But note the different position of the parentheses. This is because
@code{define} may also be used to define (lexical) variables. Hence the
following is also equivalent:

@lisp
(define foo (lambda (x) (1+ x)))
@end lisp

However this is the most uninteresting aspect of @code{define}. More
interesting is that it allows @dfn{internal definitions}.

Within a @code{define} form, any inner calls to @code{define} (that
occur in a contiguous block at the start of the body of a @code{let},
@code{let*}, @code{letrec}, @code{lambda}, or @code{define} form) are
also used to create definitions, but definitions that are local to the
containing scope. For example:

@lisp
(define (foo x)
  (define (bar)
    (* x 42))
  (1+ (bar)))
@end lisp

@noindent
This defines a top-level function called @code{foo}. However it also
contains an inner function named @code{bar}, that is only accessible
within @code{foo}. Since @code{bar} is defined inside @code{foo}, and
librep uses lexical scope by default, the variable @code{x} defined by
@code{foo} may also be accessed by @code{bar}.

@defmac define name form
@defmacx define (name . args) body-forms@dots{}
Define a global lexical variable called @var{name}, whose value will be
set to @var{form}.

If the first argument to the macro is a list, then a function is
defined whose name is @var{name} and whose formal parameters are
specified by @var{args}. The body of the function is defined by the
@var{body-forms}. The body forms have any macros expanded, and are
scanned for internal definitions (at the start of the body of
@code{let}, @code{let*}, @code{lambda} special forms)
@end defmac

@defmac define-macro name form
@defmacx define-macro (name . args) body-forms@dots{}
Similar to @code{define}, except that it creates a macro definition
(@pxref{Macros}).
@end defmac

@defmac with-internal-definitions body-forms
Recursively expand macros in @var{body-forms}, while scanning out any
internal definitions into @code{letrec} statements.
@end defmac


@node Modules, Control Structures, Definitions, The language
@section Modules
@cindex Modules

When creating large programs from many separate components, it is
important to be able to encapsulate these components, such that the
interfaces they present to other components are well defined, and the
implementations of these interfaces may be modified without affecting
any other components. To this end @code{rep} provides a @dfn{module
system} for managing the scope of global definitions. This module
system was inspired by the Scheme48, Xerox Scheme and Standard ML
module systems.

Modules are known as @dfn{structures} and may be anonymous or named.
Each structure specifies and implements an @dfn{interface}, essentially
a list of names listing the definitions within that module that may be
accessed by other modules. Each structure is a separate global
namespace, with a number of variable bindings. Each closure contains a
reference to the structure it was instantiated in, for accessing the
bindings of any free variables referenced by that closure.

As well as specifying its name and interface, each module also lists
the other modules whose bindings it may reference. Structures may
either @dfn{open} or @dfn{access} other structures; when opening a
structure all its exported bindings are immediately referenceable from
the importing module. Exported bindings from accessed structures are
referenced using the `structure-ref' form.

@menu
* Module Interfaces::
* Module Definition::
* Module Loading::
* Modules and Special Variables::
@end menu


@node Module Interfaces, Module Definition, , Modules
@subsection Module Interfaces
@cindex Modules, interfaces

Each module implements an interface---the set of bindings (i.e.
functions, macros or variables) that it exports to other modules.
Interfaces may either be defined and then referenced by name, written
literally, or combined from a number of sources.

The syntax of interface definitions is as follows:

@example
@var{interface} -> (export @var{id} @dots{})
          |  @var{name}
          |  (compound-interface @var{interface} @dots{})
          |  (structure-interface @var{module-name})
@end example

@noindent
where each @var{id} is the name of a binding to export, and each
@var{name} is the name of an interface previously defined using
@code{define-interface}.

@defmac define-interface name interface
Associate the symbol @var{name} with the module interface
@var{interface} (using one of the forms listed above.
@end defmac

Here is an example defining an interface called @code{foo}:

@lisp
(define-interface foo (compound-interface bar (export baz quux)))
@end lisp

@noindent
It includes the interface called @code{bar} and adds two extra exported
symbols: @code{baz} and @code{quux}.


@node Module Definition, Module Loading, Module Interfaces, Modules
@subsection Module Definition
@cindex Modules, definition of

Two special forms are used to define modules, one for anonymous
modules, one for named modules. When storing modules in files, each
file often contains a single instance of one of these forms.

@defmac structure interface config body@dots{}
@defmacx define-structure name interface config body@dots{}
These special forms each create a new module with interface
@var{interface} (using the syntax described in the previous section),
and configuration @var{config}.

After configuring the module as specified, the sequence of forms
@var{body@dots{}} is evaluated; it should include the definitions
required by the interface that the module has promised to implement.

The @var{config} form is either a list of configuration clauses, or a
single configuration clause. Each such clause must be of the following
syntax:

@example
@var{clause} -> (open @var{name} @dots{})
       |  (access @var{name} @dots{})
@end example

@noindent
Each @var{name} specifies the name of a module, in the case of
@code{open} clauses, the named module(s) will be loaded such that their
exported bindings may be referenced from within the current module with
no qualification (i.e. as if they had been defined within the module
itself).

Alternatively, if an @code{access} clause was used, the named module(s)
will be loaded, but their exported bindings will only be accessible
from within the current module using the @code{structure-ref} form.
E.g. if a module @code{foo} has been accessed and it exports a binding
named @code{bar}, then the following form could be used to access its
value:

@lisp
(structure-ref foo bar)
@end lisp

@noindent
Since this form is used so often, the reader allows the abbreviation
@code{foo#bar} to be used instead, it is expanded to the form above
when read. Note that no whitespace is allowed between the three tokens.
@end defmac

Note that to access the standard features of the @code{rep} language
described in this manual, modules need to import the @code{rep} module.
Alternatively, they may import the @code{scheme} module to load a
minimal R4RS Scheme environment.

Here is an example module definition, defining a module named
@code{test} that exports two functions @code{foo} and @code{bar}.

@lisp
(define-structure test (export foo bar)
    (open rep)
  (define (foo x) (* x 42))
  (define (bar x y) (+ (foo x) (1+ y))))
@end lisp

It is also possible to export multiple views of a single underlying set
of bindings, by using the @code{define-structures} form to create a
number of modules.

@defmac define-structures ((name interface) @dots{}) config body@dots{}
Create a module for each @code{(@var{name} @var{interface})} pair. The
module is called @var{name} and exports the interface defined by
@var{interface}.

The @var{config} and @var{body@dots{}} forms are as in
@code{define-structure}.

Here is a trivial example:

@lisp
(define-structures ((foo (export foo both))
                    (bar (export bar both)))
    (open rep)
  (define both 1)
  (define foo 2)
  (define bar 3))
@end lisp

@noindent
the underlying environment has three bindings. Each created module
exports two of these.
@end defmac


@node Module Loading, Modules and Special Variables, Module Definition, Modules
@subsection Module Loading
@cindex Modules, loading

As described above, the common way of loading modules is to use the
@code{open} and @code{access} clauses of the configuration language.

If the modules named by these clauses are not currently loaded into the
interpreter, then the system will attempt to load them from the filing
system, using the standard @code{load-path} variable to define the
directories to search.

To allow modules names to be hierarchical, any dot characters in a
module's name are replaced by the operating system's directory
separator string (i.e. on unix, all @samp{.} characters are simply
replaced by @samp{/} characters).

When searching for files to load, the standard filename suffixes are
used to differentiate Lisp files from other types of files (@pxref{Load
Function}). This file should contain a @code{define-structure} form (as
described in the previous section) as the last top-level form in the
file.

For backwards compatibility, the @code{require} function can also be
used to import modules. If a module of the same name as the requested
feature has already been loaded, then it is imported into the current
module. Otherwise if a file is loaded that contains a module definition
as its last top-level form, this module is imported into the current
module. @xref{Features}.


@node Modules and Special Variables, , Module Loading, Modules
@subsection Modules and Special Variables
@cindex Modules, and special variables

As described earlier, the @code{defvar} special form may be used to
create variables that are scoped dynamically, known as special
variables, see @ref{Defining Variables}. Due to their dynamic scope,
special variables do not fit well with the lexically scoped module
system described here.

As a result of this mismatch, special variables are stored in a
separate namespace. This means that modules defining special variables
must take the necessary steps to avoid the names of these variables
clashing with those declared in other modules@footnote{The usual
convention is to prefix the variable name with a unique string derived
from the module name.}. 

In fact, it is often advisable to avoid using special variables as much
as possible, especially when writing modules of Lisp code. An
alternative method of creating dynamically scoped variables is to use
fluid variable objects. These use first class Lisp objects to represent
anonymous dynamically scoped variables. Since they are just Lisp
objects, they may be stored in lexically scoped variables---this gives
the benefits of both lexical (i.e. encapsulation) and dynamic scoping.
@xref{Fluid Variables}.


@node Control Structures, Threads, Modules, The language
@section Control Structures
@cindex Control Structures

Control structures are special forms or macros that control
@emph{which} forms get evaluated, @emph{when} they get evaluated and
the @emph{number} of times to evaluate them. This includes conditional
structures, loops, etc@dots{}

The simplest control structures are the sequencing structures; they are
used to evaluate a list of forms in left to right order.

@menu
* Sequencing Structures::       Evaluating several forms in sequence
* Conditional Structures::      Making decisions based on truth values
* Looping Structures::          `while' loops
* Non-Local Exits::             Exiting from several levels of evaluation
* Continuations::               Capturing the call stack
@end menu


@node Sequencing Structures, Conditional Structures, , Control Structures
@subsection Sequencing Structures
@cindex Sequencing structures
@cindex Control structures, sequencing

Each of the special forms in this section simply evaluates its
arguments in left-to-right order. The only difference is the result
returned.

The most widely used sequencing special form is @code{progn}: it
evaluates all its argument forms and returns the computed value of the last
one. Many other control structures are said to perform an @dfn{implicit progn},
this means that internally they call @code{progn} with a list of forms.

@code{progn} in Lisp is nearly analogous to a @code{begin@dots{}end}
block in Pascal; it is used in much the same places---to allow you to
evaluate a sequence of form where only one form was allowed (for
example the ``true'' clause of an @code{if} structure).

@defspec progn forms@dots{}
All of the @var{forms} are evaluated sequentially (from left-to-right),
the result of the last evaluated @var{form} is the return value of the
special form. If no arguments are given to @code{progn} it returns
false.

@lisp
(progn 'one (+ 1 1) "three")
    @result{} "three"

(progn)
    @result{} ()
@end lisp
@end defspec

@defmac prog1 first forms@dots{}
This special form evaluates its @var{first} form then performs an
implicit progn on the rest of its arguments. The result of this
structure is the computed value of the @var{first} form.

@lisp
(prog1 'one (+ 1 1) "three")
    @result{} one
@end lisp
@end defmac

@defmac prog2 first second forms@dots{}
This is similar to @code{prog1} except that the evaluation of its
@var{second} form is returned.

The @var{first} form is evaluated, then its @var{second}, then it
performs an implicit progn on the remaining arguments.

@lisp
(prog2 'one (+ 1 1) "three")
    @result{} 2
@end lisp
@end defmac


@node Conditional Structures, Looping Structures, Sequencing Structures, Control Structures
@subsection Conditional Structures
@cindex Conditional structures
@cindex Control structures, conditionals

Lisp provides a number of conditional constructs, the most complex of
which (@code{cond}) takes a list of conditions, the first of which
evaluates to true has its
associated list of forms evaluated. Theoretically this is the only
conditional special form necessary---all others can be implemented as
macros.

@defmac if condition true-form else-forms@dots{}
The @code{if} form is the nearest thing in Lisp to the
@dfn{if-then-else} construct found in most programming languages.

First the @var{condition} form is evaluated, if it returns true the
@var{true-form} is evaluated and its result returned. Otherwise the
result of an implicit progn on the @var{else-forms} is returned. If
there are no @var{else-forms} false is returned.

Note that one of the @var{true-form} or the @var{else-forms} is completely
ignored---it is not evaluated.

@lisp
(if (special-form-p if)
    "`if' is a special form"
  "`if' is not a special form")
    @result{} "`if' is not a special form"
@end lisp
@end defmac

@defmac when condition true-forms@dots{}
@var{condition} is evaluated, if it is true the result of an
implicit progn on the @var{true-forms} is returned, otherwise
false is returned.

@lisp
(when t
  (message "Pointless")
  'foo)
    @result{} foo
@end lisp
@end defmac

@defmac unless condition else-forms@dots{}
This special form evaluates @var{condition}, if its computed value is
true, @code{()} is returned. Otherwise the @var{else-forms} are
evaluated sequentially, the value of the last is returned.
@end defmac

@defspec cond clause@dots{}
The @code{cond} special form is used to choose between an arbitrary
number of conditions. Each @var{clause} is a list; the car of which is
a @var{condition}, the cdr is a list of forms to evaluate (in an
implicit @code{progn}) if the @var{condition} evaluates to true.
This means that each @var{clause} looks something like:

@lisp
(@var{condition} @var{body-forms}@dots{})
@end lisp

@noindent
and a whole @code{cond} form looks like:

@lisp
(cond
 (@var{condition-1} @var{body-forms-1}@dots{})
 (@var{condition-2} @var{body-forms-2}@dots{})
 @dots{})
@end lisp

The @var{condition} in each @var{clause} is evaluated in sequence
(@var{condition-1}, then @var{condition-2}, @dots{}), the first one
which evaluates to a true value has an implicit @code{progn}
performed on its @var{body-forms}. The value of this @code{progn} is
also the value of the @code{cond} statement.

If the true @var{condition} has no @var{body-forms} the value returned
is the value of the @var{condition}. If none of the clauses has a
true @var{condition} the value of the @code{cond} statement
is false.

Often you want a @dfn{default} clause which has its @var{body-forms}
evaluated when none of the other clauses are true. The way to do this
is to add a clause with a @var{condition} of @code{t} and
@var{body-forms} of whatever you want the default action to be.

@lisp
(cond
 ((stringp buffer-list))        ;Clause with no @var{body-forms}
 ((consp buffer-list)
  (setq x buffer-list)          ;Two @var{body-forms}
  t)
 (t                             ;Default clause
  (error "`buffer-list' is corrupted!")))
    @result{} t
@end lisp
@end defspec

@defmac case key clauses@dots{}
This special form is similar to @code{cond}, but switches on the result
of evaluating a single form @var{key}, checking for equality with a
number of other values, defined by the @var{clauses}. If any of these
other values is the same as the result of evaluating @var{key}, then a
sequence of forms associated with the value is evaluated.

Each element of the @var{clauses} list has the format:

@lisp
((@var{value-1} @var{value-2} @dots{} @var{value-n}) @var{forms}@dots{})
@end lisp

@noindent
Each of the values in the car of the clause is tested for equality with
@var{key}, using the @code{eql} function. If any test positively, then
the associated @var{forms} are evaluated and the resulting value
becomes the result of the special form.

Instead of supplying a list of possible values, it is also possible to
just specify the symbol @code{t}. If such a clause is encountered, and
no other clauses have matched the value of @var{key}, then this clause
is assumed to match by default.

If any of the values in the @var{clauses} appear multiply, then the
behaviour of the construct is undefined.

Here is an example use of @code{case}:

@lisp
(case foo
  ((bar baz)
    (print "It was either bar or baz"))
  ((quux)
    (print "It was quux"))
  (t
    (print "I've no idea what it was...")))
@end lisp
@end defmac

There are also a number of special forms which combine conditions together
by the normal logical rules.

@defmac or forms@dots{}
The first of the @var{forms} is evaluated, if it is true its
value is the value of the @code{or} form and no more of @code{forms}
are evaluated. Otherwise this step is repeated for the next member of
@var{forms}.

If all of the @var{forms} have been evaluated and none have a
true value the @code{or} form evaluates to false.

@lisp
(or nil 1 nil (beep))           ;@code{(beep)} won't be evaluated
    @result{} 1
@end lisp
@end defmac

@defmac and forms@dots{}
The first of the @var{forms} is evaluated. If it is false no more
of the @var{forms} are evaluated and false is the value of
the @code{and} statement. Otherwise the next member of @var{forms} is
evaluated and its value tested. If none of the @var{forms} are
false the computed value of the last member of @var{forms} is
returned from the @code{and} form.

@lisp
(and 1 2 nil (beep))            ;@code{(beep)} won't be evaluated
    @result{} ()

(and 1 2 3)                     ;All forms are evaluated
    @result{} 3
@end lisp
@end defmac

@defun not object
This function inverts the truth value of its argument. If @var{object}
is true, false is returned, otherwise true is
returned.

@lisp
(not nil)
    @result{} t

(not t)
    @result{} ()

(not (not 42))
    @result{} t
@end lisp
@end defun


@node Looping Structures, Non-Local Exits, Conditional Structures, Control Structures
@subsection Looping Structures
@cindex Looping structures
@cindex Control structures, looping

The @code{librep} Lisp dialect only has one method of creating looping
control structures---recursion. Any looping construct found in an
imperative language can be represented as a recursive function. For
example the common @code{while} statement:

@lisp
(while @var{condition} @var{body}@dots{})
@equiv{}
(letrec ((loop (lambda ()
                 (when @var{condition}
                   @var{body}
                   (loop)))))
  (loop))
@end lisp

@noindent
Each successive iteration of the loop is simply another call to the
function. Also note that the recursive call to the @code{(loop)}
function occurs in the tail-position of the function. When combined
with the system's ability to eliminate tail-calls (@pxref{Function Call
Forms}) the above example loop has bounded space requirements. This is
important when loops make a large number of iterations.

Although tail-recursion is the only primitive method of looping, the
language offers a number of looping forms for convenience.

@defmac do vars (test expr@dots{}) body@dots{}
@code{do} is an iteration construct; @var{vars} specifies a set of
variable bindings to be created, how they are initialized and how they
are updated on each iteration. @var{test} specifies the termination
condition of the loop, any @var{expr}@dots{} forms are evaluated
immediately prior to exiting the `do' construct. The @var{body}@dots{}
forms specify the side effecting body of the loop.

@var{vars} is a list of variable clauses, each of which has the
structure @code{(@var{variable} @var{init} @var{step})} where
@var{variable} is the name of a variable, @var{init} defines the
initial value of its binding, and @var{step} defines how the next value
of the binding is computed. An alternative form is
@code{(@var{variable} @var{init})}, in this case the value of the
binding does not change across loop iterations.

Each iteration begins by evaluating @var{test}, if the result is
false, then the @var{body}@dots{} expressions are evaluated, and
the variables bound to new locations initialized to the results of
evaluating the associated @var{step} forms.

If the result of evaluating @var{test} is true then the
@var{expr}@dots{} forms are evaluated, and the @code{do} construct
returns the value of the last @var{expr} form evaluated.

@lisp
(do ((vec (make-vector 5))
     (i 0 (1+ i)))
    ((= i 5) vec)
  (aset vec i i))

    @result{} [0 1 2 3 4]
@end lisp
@end defmac

The ``named-let'' variant of the @code{let} form also provides a
convenient looping construct.

@defmac let variable bindings body@dots{}
This is the same as the @code{(let @var{bindings} @var{body}@dots{})}
form described in @ref{Local Variables}, but within the
@var{body}@dots{} forms, the symbol @var{variable} is bound to a
function whose parameters are the bound variables defined by
@var{bindings} and whose body is the sequence of forms
@var{body}@dots{}

This means that the body of the @code{let} may be repeated by invoking
the function @var{variable} with suitable parameters.

@lisp
(let loop ((rest '(1 2 3))
           (total 0))
  (if (null rest)
      total
    (loop (cdr rest) (+ total (car rest)))))

    @result{} 6
@end lisp
@end defmac

Finally, the imperative @code{while} form shown at the start of the
section is also provided:

@defmac while condition body@dots{}
The @var{condition} form is evaluated. If it is true an
implicit progn is performed on the @var{body} forms and the whole
procedure is repeated.

This continues until the @var{condition} form evaluates to false.
The value of every @code{while} structure that terminates is
false.
@end defmac


@node Non-Local Exits, Continuations, Looping Structures, Control Structures
@subsection Non-Local Exits
@cindex Non-local exits
@cindex Control structures, non-local exits

A @dfn{non-local exit} is a transfer of control from the current point
of evaluation to a different point (somewhat similar to the
much-maligned @code{goto} statement in imperative languages).

Non-local exits can either be used explicitly (@code{catch} and
@code{throw}) or implicitly (errors).

@menu
* Catch and Throw::             Programmed non-local exits
* Function Exits::              Returning values from a function
* Cleanup Forms::               Forms which will always be evaluated
* Errors::                      Signalling that an error occurred
@end menu


@node Catch and Throw, Function Exits, , Non-Local Exits
@subsubsection Catch and Throw
@cindex Catch and throw
@cindex Non-local exits, catch and throw

The @code{catch} and @code{throw} structures are used to perform
explicit transfers of control. First a @code{catch} form is used to
setup a @dfn{tag}; this acts like a label for a @code{goto} statement.
To transfer control a @code{throw} form is then used to transfer to the
named tag. The tag is destroyed and the @code{catch} form exits with
the value provided by the @code{throw}.

In a program this looks like,

@lisp
(catch '@var{tag}
  ;; Forms which may `throw' back to @var{tag}
  @dots{}
  (throw '@var{tag} @var{value})
  ;; Control has now passed to the `catch',
  ;; no more forms in this progn will be evaluated.
  @dots{})
    @result{} @var{value}
@end lisp

@noindent
where @var{tag} is the tag to be used (this is normally a symbol) and
@var{value} is the result of the @code{catch} form.

When a throw actually happens all catches in scope are searched for one
with a tag which is @code{eq} to the tag in the throw. If more than one
exists the innermost is selected. Now that the catch has been located
the environment is `wound-back' to the catch's position (i.e. local
variables are unbound, cleanup forms executed, unused catches removed,
etc@dots{}) and all Lisp constructs between the current point of
control and the catch are immediately exited.

For example,

@lisp
(let
    ((test 'outer))
  (cons (catch 'foo
          (let
              ((test 'inner))
            (throw 'foo test)
            (setq test 'unreachable)))  ;Never reached
        test))
    @result{} (inner . outer)
@end lisp

@noindent
when the throw executes the second binding of @code{test} is unwound
and the first binding comes back into effect. For more details on
variable binding see @ref{Local Variables}.

Note that catch tags are @emph{dynamically} scoped, the thrower does
not have to be within the same lexical scope (this means that you can
@code{throw} through functions).

@defmac catch tag body-forms@dots{}
This special form defines a catch tag which will be accessible while the
@var{body-forms} are evaluated.

@var{tag} is evaluated and recorded as the tag for this catch. Next the
@var{body-forms} are evaluated as an implicit @code{progn}. The value
of the @code{catch} form is either the value of the @code{progn}, or,
if a @code{throw} happened, the value specified in the @var{throw}
form.

Before exiting, the tag installed by this form is removed.
@end defmac

@defun throw tag @t{#!optional} catch-value
This function transfers the point of control to the catch form with a
tag which is @code{eq} to @var{tag}. The value returned by this catch
form is either @var{catch-value} or false if @var{catch-value} is
undefined.

If there is no catch with a tag of @var{tag} an error is signalled and
the interpreter returns to the top-level of evaluation.
@end defun

There are a number of pre-defined throw tags:

@table @code
@item quit
Terminate the @code{librep} interpreter, returning the value of the
throw (if a number).

@item exit
Exit the innermost event loop, unless currently in the outermost event
loop, when control just passes back to the event loop.

@item user-interrupt
As if a @code{SIGINT} or @kbd{C-c} signal has been received. Control
passes back to the top-level event loop.

@item term-interrupt
Triggered when a @code{SIGTERM} or @code{SIGHUP} signal is received.
Tries to clean up any existing state, then terminates the interpreter.
@end table

Note that it is the event loop that catches these tags. If no event
loop is active (i.e. just in read-eval-print on the console mode), any
uncaught throws will result in termination.


@node Function Exits, Cleanup Forms, Catch and Throw, Non-Local Exits
@subsubsection Function Exits
@cindex Function exits
@cindex Non-local exits, function exits

@code{librep} has no explicit @code{return} statement, as found in most
other languages. Where a value has to returned from a function before
the function would normally exit, a @code{catch}/@code{throw} pair may
be used.

For example:

@lisp
(defun foo (x y)
  (catch 'return
     (when (= x 2)
       (throw 'return nil))
     @dots{}
@end lisp


@node Cleanup Forms, Errors, Function Exits, Non-Local Exits
@subsubsection Cleanup Forms
@cindex Cleanup forms
@cindex Non-local exits, cleanup forms

It is sometimes necessary ensure that a certain form is @emph{always}
evaluated, even when a non-local exit would normally bypass that form.
The @code{unwind-protect} special form is used in this case.

@defmac unwind-protect body-form cleanup-forms@dots{}
The @var{body-form} is evaluated, if it exits normally the @var{cleanup-forms}
are evaluated sequentially then the value which the @var{body-form}
returned becomes the value of the @code{unwind-protect} form. If the
@var{body-form} exits abnormally though (i.e. a non-local exit happened)
the @var{cleanup-forms} are evaluated anyway and the non-local exit
continues.
@end defmac

One use of this is to ensure that an opened file is always closed, for
example,

@lisp
(catch 'foo
  (unwind-protect
      (let
          ((temporary-file (open-file (make-temp-name) 'write)))
        ;; Use @code{temporary-file}
        (write temporary-file "A test\n")
        ;; Now force a non-local exit
        (throw 'foo))
    ;; This is the @var{cleanup-form} it will @emph{always}
    ;; be evaluated, despite the @code{throw}.
    (close temporary-file)))
    @result{} ()
@end lisp


@node Errors, , Cleanup Forms, Non-Local Exits
@subsubsection Errors
@cindex Errors
@cindex Non-local exits, errors

Errors are a type of non-local exit; when a form can not be evaluated
for some reason an error is normally @dfn{signalled}. If an
error-handler has been installed for that type of error, control is
passed to the handler for that error, and evaluation continues. If
there is no suitable handler, control is passed back to the innermost
input loop and a suitable error message is printed.

@defun signal error-symbol data
Signals that an error has happened. @var{error-symbol} is a symbol
classifying the type of error, it should have a property
@code{error-message} (a string) which is the error message to be
printed.

@var{data} is a list of objects which are relevant to the error ---
they will be made available to any error-handler or printed with the
error message otherwise.

@lisp
(signal 'void-value '(some-symbol))
    @error{} Value as variable is void: some-symbol
@end lisp
@end defun

@defvar debug-on-error
This variable is consulted by the function @code{signal}. If its value
is either @code{t} or a list containing the @var{error-symbol} to
@code{signal} as one of its elements, the Lisp debugger is entered.
When the debugger exits the error is signalled as normal.
@end defvar

@defvar backtrace-on-error
Similar to @code{debug-on-error}, but if an error is matched, the
current backtrace is printed to the standard error stream, and control
continues.
@end defvar

When you expect an error to occur and need to be able to regain control
afterwards the @code{condition-case} special form may be used.

@defmac condition-case symbol body-form error-handlers@dots{}
@code{condition-case} evaluates the @var{body-form} with the
@var{error-handlers} in place. If an error occurs and one of the
handles matches the error, then it is evaluated with the value of
@var{symbol} set to the error information.

Each of the @var{error-handlers} is a list whose car is a symbol
defining the type of error which this handler catches. The cdr of the
list is a list of forms to be evaluated in a @code{progn} if the
handler is invoked.

While the forms of the error handler are being evaluated the variable
@var{symbol} is bound to the value @code{(@var{error-symbol} .
@var{data})} (these were the arguments to the @code{signal} form which
caused the error). If @var{symbol} is the symbol @code{nil} (or the
empty list @code{()}), then the error information is not available to
the handler.

The special value, the symbol @code{error}, in the car of one of the
@var{error-handlers} will catch @emph{all} types of errors.

@lisp
(condition-case data
    (signal 'file-error '("File not found" "/tmp/foo"))
  (file-error
   data)
  (error
   (setq x z)))         ;Default handler
    @result{} (file-error "File not found" "/tmp/foo")
@end lisp
@end defmac


@node Continuations, , Non-Local Exits, Control Structures
@section Continuations
@cindex Continuations

Whenever a function is called, there is a control path waiting to
receive the result of the function, e.g. often the form following the
function invocation. This waiting control path is called the
@dfn{continuation} of the function, since control will continue down
this path when the called function exits.

These continuations are usually not paid much thought, but in some
cases it may be useful to be able to directly manipulate the
continuation of a function. For this purpose rep provides the
@code{call-with-current-continuation} function (often shortened to
@code{call/cc}) that is standard in the Scheme dialect of Lisp.

@defun call/cc function
@var{function} is a function with a single parameter; it will be
immediately invoked with this parameter bound to an object representing
the current continuation (i.e. the control path that would be taken
after @var{function} exits).

The continuation object passed to @var{function} is itself a function
accepting a single argument, when called it transfers control to the
continuation of @var{function}, as if @var{function} had returned the
argument applied to the continuation object.
@end defun

@defun call-with-current-continuation function
This is an alias for @code{call/cc}.
@end defun

In its simplest form, @code{call/cc} can mimic the @code{catch} and
@code{throw} procedures (@pxref{Catch and Throw}), for example:

@lisp
(defun foo (bar)
  (call/cc (lambda (esc)
             (when (null bar)
               ;; throws out of the call/cc
               (esc nil))
             ;; do something with bar
             @dots{}
@end lisp

@noindent
this is roughly equivalent to:

@lisp
(defun foo (bar)
  (catch 'tag
    (when (null bar)
      (throw 'tag nil))
    ;; do something with bar
    @dots{}
@end lisp

This is only half the story---the most powerful feature of
@code{call/cc} is that since continuations have dynamic extent (that
is, no object is freed until no references to it exist) it is possible
to return control to scopes that have already exited.

For example, consider the following fragment of a lisp interaction:

@lisp
(prog1 (call/cc (lambda (esc)
                  (setq cont esc)))
  (message "foo!"))
    @print{} foo!
    @result{} #<closure>

cont
    @result{} #<closure>

(cont 10)
    @print{} foo!
    @result{} 10
@end lisp

@noindent
The continuation of the @code{prog1} form is saved into the variable
@code{cont}. When subsequently called with a single argument, it has
exactly the same effect as the first time that the second form in the
@code{prog1} construct was evaluated.

@subsection Implementation Notes

@code{call/cc} works by making a copy of the process' entire call
stack. For this reason, it is likely to be less efficient than using
the control structures described in the previous parts of this section.
Of course, it is much more powerful than the other constructs, so this
often outweighs the slight inefficiency.

Also note that currently no attempt is made to save or restore the
dynamic state of the Lisp system, apart from variable bindings (both
lexical and special). This means that any @code{unwind-protect},
@code{condition-case} or @code{catch} forms that are active when
invoking a continuation are all ignored.

Another restriction is that invoking a continuation may not cause
control to pass across a dynamic root (@pxref{Threads}).


@node Threads, Loading, Control Structures, The language
@section Threads
@cindex Threads

@code{librep} supports a simple model of multi-threaded programming.
Multiple threads of execution may be created, with control preemptively
being switched between them.

Unless otherwise noted, all definitions described in this section are
provided by the @code{rep.threads} module.

@menu
* Thread Contexts::
* Creating Threads::
* Deleting Threads::
* Manipulating Threads::
* Mutexes::
* Thread Implementation Notes::
@end menu


@node Thread Contexts, Creating Threads, , Threads
@subsection Thread Contexts
@cindex Thread contexts

Every thread created by rep is a member of a @dfn{thread context}, this
context is defined by the current position in the lisp call stack. At
any point in time, only threads which are members of the current
context may be executing.

@defun call-with-dynamic-root thunk
Call the function of zero-parameters @var{thunk} in a new thread
context. The new context will contain a single thread, that executing
@var{thunk}.

The call to @code{call-with-dynamic-root} will only return once all
threads in the newly created context have been deleted, or a non-local
exit causes control to leave forcibly.
@end defun


@node Creating Threads, Deleting Threads, Thread Contexts, Threads
@subsection Creating Threads
@cindex Creating threads
@cindex Threads, creating

The @code{make-thread} function may be used to create threads that
execute within the current thread context (dynamic root). Each thread
is represented by a lisp object.

@defun threadp arg
Return true if lisp object @var{arg} represents a thread of
execution in the lisp environment.
@end defun

@defun make-thread thunk @t{#!optional} name
Create and return a new thread of execution; it will initially invoke
the zero-parameter function @var{thunk}. If the call to @var{thunk}
returns the thread is automatically deleted.

If @var{name} is defined, it is a string naming the current thread.
@end defun

@defun make-suspended-thread @t{#!optional} name
Similar to @code{make-thread}, except that the newly created thread
will be immediately suspended from running.
@end defun

@defun current-thread
Returns the currently executing thread. If no threads have been created
yet in the current dynamic root (i.e. there is a single ``implicit''
thread) then false is returned.
@end defun

@defun all-threads
Returns a newly-created list containing all threads in the current
dynamic root. If no threads have been created yet, returns a null list.
@end defun


@node Deleting Threads, Manipulating Threads, Creating Threads, Threads
@subsection Deleting Threads
@cindex Deleting threads
@cindex Threads, deleting

A thread may be deleted by either returning from the function specified
when it was created, or by explicit deletion. Also, the implicit thread
created by the @code{call-with-dynamic-root} function may be deleted by
exiting from the function called in the new context.

@defun thread-delete @t{#!optional} thread
Mark @var{thread} (or the current thread), as being deleted. It will
not be switched to in the future. If the current thread is deleted,
control will be passed to the next runnable thread. Deleting the last
runnable thread results forces the containing dynamic root to be
closed.
@end defun

@defun thread-deleted-p thread
Returns true if @var{thread} has been deleted.
@end defun


@node Manipulating Threads, Mutexes, Deleting Threads, Threads
@subsection Manipulating Threads
@cindex Manipulating threads
@cindex Threads, manipulating

@defun thread-yield
This function may be used to pass control away from the current thread
if other threads are waiting to run. There is usually no need to call
this function since running threads will be preempted after a period of
time.
@end defun

@defun thread-suspend @t{#!optional} thread milliseconds
Mark @var{thread} (or the current thread) as being suspended. It will
not be selected until either it has had this status removed, or
@var{milliseconds} milliseconds time has passed.

Suspending the current thread will pass control to the next runnable
thread in the same dynamic root. If there are no runnable threads, then
the interpreter will sleep until the next thread becomes runnable.
@end defun

@defun thread-join thread @t{#!optional} timeout default-value
Suspends the current thread until either @var{thread} has exited, or
@var{timeout} milliseconds have passed.

If @var{thread} exits normally, then the value of the last form it
evaluated is returned; otherwise @var{default-value} is returned.

It is an error to call @code{thread-join} on a @var{thread} that is not
a member of the current dynamic root.
@end defun

@defun thread-wake thread
Remove the suspended state from thread @var{thread}. It will then be
scheduled for execution sometime subsequently, if its dynamic root is
active.
@end defun

@defun thread-suspended-p thread
Returns true if @var{thread} is currently suspended.
@end defun

Thread preemption may be forbidden at times, to allow atomic operations
to take place. Each dynamic root has its own ``forbid counter''. Only
when this counter is zero may the current thread be preempted.

@defun thread-forbid
Increment the forbid count.
@end defun

@defun thread-permit
Decrement the forbid count.
@end defun

@defmac without-interrupts @t{#!rest} forms
Evaluate the list of forms @var{forms} with thread preemption
temporarily disabled.
@end defmac


@node Mutexes, Thread Implementation Notes, Manipulating Threads, Threads
@subsection Mutual Exclusion Devices
@cindex Mutual exclusion devices
@cindex Mutexes
@cindex Threads, mutexes

@dfn{Mutexes} are lisp objects used to coordinate access to data shared
across multiple threads (where interleaved access would be bad). These
functions are exported by the @code{rep.threads.mutex} module
(@pxref{Modules}).

@defun make-mutex
Create and return a mutex object. No thread will own the new mutex.
@end defun

@defun mutexp arg
Return true if @var{arg} is a mutex object.
@end defun

@defun obtain-mutex mutex
Obtain the mutex @var{mutex} for the current thread. Will suspend the
current thread until the mutex is exclusively available.
@end defun

@defun maybe-obtain-mutex mutex
Attempt to obtain mutex @var{mutex} for the current thread without
blocking. Returns true if able to obtain the mutex, false
otherwise.
@end defun

@defun release-mutex mutex
Release the mutex object @var{mutex} (which must have previously been
obtained by the current thread). Returns true if the mutex has no
new owner.
@end defun


@node Thread Implementation Notes, , Mutexes, Threads
@subsection Thread Implementation Notes
@cindex Thread implementation notes

The threads used by @code{librep} are @emph{software threads}. This
means that they are currently implemented by manually switching in and
out thread context (i.e. the call stack) as required. There are a
number of disadvantages to this method:

@itemize @bullet
@item blocking I/O blocks @emph{all} threads, not just the thread doing
the I/O,

@item only a single processor is used, thereby avoiding any true
parallelism on multi-processor systems.
@end itemize

@noindent
The main advantage is the ease of implementation, especially when
retrofitting threads into the previously single-threaded interpreter.


@node Loading, Compiled Lisp, Threads, The language
@section Loading
@cindex Loading
@cindex Loading programs
@cindex Programs, loading

In Lisp, programs (also called @dfn{modules}, or @dfn{libraries}) are
stored in files. Each file is a sequence of Lisp forms (known as
@dfn{top-level forms}). Most of the top-level forms in a program will
be definitions (i.e. function, macro or variable definitions) since
generally each library is a system of related functions and variables.

Before the program can be used it has to be @dfn{loaded} into the editor's
workspace; this involves reading and evaluating each top-level form in
the file, i.e. instantiating all function definitions, or whatever.

@menu
* Load Function::               The function which loads programs
* Autoloading::                 Functions can be loaded on reference
* Features::                    Module management functions
@end menu


@node Load Function, Autoloading, , Loading
@subsection Load Function
@cindex Load function
@cindex Functions, loading

@defun load program @t{#!optional} no-error no-path no-suffix
This function loads the file containing the program called @var{program};
first the file is located then each top-level form contained by the file
is read and evaluated in order.

Each directory named by the variable @code{load-path} is searched until
the file containing @var{program} is found. In each directory three
different file names are tried,

@enumerate
@item
@var{program} with @samp{.jlc} appended to it. Files with a @samp{.jlc}
suffix are usually compiled Lisp files. @xref{Compiled Lisp}.

@item
@var{program} with @samp{.jl} appended, most uncompiled Lisp programs are
stored in files with names like this.

@item
@var{program} with no modifications.
@end enumerate

If none of these gives a result the next directory is searched in the
same way, when all directories in @code{load-path} have been exhausted
and the file still has not been found an error is signalled.

Next the file is opened for reading and Lisp forms are read from it
one at a time, each form is evaluated before the next form is read. When
the end of the file is reached the file has been loaded and this function
returns true.

The optional arguments to this function are used to modify its behaviour,

@table @var
@item no-error
When this argument is true no error is signalled if the file
can not be located. Instead the function returns false.

@item no-path
The variable @code{load-path} is not used, @var{program} must point to
the file from the current working directory.

@item no-suffix
When true no @samp{.jlc} or @samp{.jl} suffixes are applied to
the @var{program} argument when locating the file.
@end table

If a version of the program whose name ends in @samp{.jlc} is older than
a @samp{.jl} version of the same file (i.e. the source code is newer than
the compiled version) a warning is displayed and the @samp{.jl} version
is used.

If no Lisp file can be found matching @var{program}, then each
directory in the variable @code{dl-load-path} is searched for a
@code{libtool} shared library called @file{@var{program}.la}
(@pxref{Shared Libraries}).
@end defun

@defvar load-filename
Whilst loading a Lisp library, this variable is bound to the name of
the file being loaded.
@end defvar

@defvar load-path
A list of strings, each element is the name of a directory which is
prefixed to the name of a program when Lisp program files are being
searched for.

@lisp
load-path
    @result{} ("/usr/local/lib/rep/1.0/lisp/"
        "/usr/local/lib/rep/site-lisp/" "")
@end lisp

The element @code{""} refers to the current directory, note that
directory names should have an ending @samp{/} (or whatever) so that
when concatenated with the name of the file they make a meaningful
filename.
@end defvar

@defvar dl-load-path
A list of strings defining all directories to search for shared
libraries.
@end defvar

@defvar lisp-lib-directory
The name of the directory in which the standard Lisp files are stored.

@lisp
lisp-lib-dir
    @result{} "/usr/local/lib/rep/1.0/lisp/"
@end lisp
@end defvar

@defvar after-load-alist
An association list of elements of the format @code{(@var{file}
@var{forms} @dots{})}. When the library @var{file} is loaded, all
@var{forms} are executed. However, note that @var{file} must
@emph{exactly} match the @var{program} argument to the @code{load}
function.
@end defvar

@defun eval-after-load library form
Arrange for @var{form} to be evaluated immediately after the Lisp
library of @var{library} has been read by the @code{load} function.
Note that @var{library} must exactly match the @var{program} argument
to @code{load}.
@end defun


@node Autoloading, Features, Load Function, Loading
@subsection Autoloading
@cindex Autoloading
@cindex Loading, on reference

Obviously, not all features of the @code{librep} environment are always
used. @dfn{Autoloading} allows libraries to only be loaded when they
are first required. This speeds up the initialisation process and may
save memory.

Functions which may be autoloaded have a special form in their symbol's
function cell---an @dfn{autoload form}. This is a special kind of
closure. When the function call dispatcher finds one of these forms it
loads the program file specified in the form then re-evaluates the
function call. The true function definition will then have been loaded
and therefore the call may proceed as normal.

Autoload stubs may be created through the @code{autoload} function.

@defun autoload symbol file @t{#!optional} is-command
Installs an autoload form into the symbol @var{symbol}. It marks that
when @var{symbol} is called as a function the lisp library @var{file}
should be loaded to provided the actual definition of @var{symbol}.
@end defun

It is not necessary to call the @code{autoload} function manually.
Simply prefix the definitions of all the functions that may be
autoloaded (i.e. the entry points to your module; @emph{not} all the
internal functions.) with the magic comment @code{;;;###autoload}. Then
load the file into the Jade editor and invoke the @code{add-autoloads}
command, creating all the necessary calls to the autoload function in
the @file{autoloads.jl} Lisp file (this file which lives in the Lisp
library directory is loaded when the environment is initialised).

@table @kbd
@item Meta-x add-autoloads
@kindex Meta-x add-autoloads
Scans the current buffer for any autoload definitions. Functions with
the comment @code{;;;###autoload} preceding them have autoload forms
inserted into the @file{autoloads.jl} file. Simply save this file's
buffer and the new autoloads will be used the next time Jade is
initialised.

It is also possible to mark arbitrary forms for inclusion in the
@file{autoloads.jl} file: put them on a single line which starts with
the comment @code{;;;###autoload} call the command.

The unsaved @file{autoloads.jl} buffer will become the current buffer.

@lisp
;;;###autoload
(defun foo (bar)                ;@code{foo} is to be autoloaded
  @dots{}

;;;###autoload (setq x y)       ;Form to eval on initialisation
@end lisp

@item Meta-x remove-autoloads
@kindex Meta-x remove-autoloads
Remove all autoload forms from the @file{autoloads.jl} file which
are marked by the @code{;;;###autoload} comment in the current buffer.

The unsaved @file{autoloads.jl} buffer will become the current buffer.
@end table

XXX these editor commands don't really belong here, but they'll do for
now@dots{}


@node Features, , Autoloading, Loading
@subsection Features
@cindex Features

@dfn{Features} correspond to libraries of Lisp code. Each feature is
loaded separately. Each feature has a name, when a certain feature is
required its user asks for it to be present (with the @code{require}
function), the feature may then be used as normal.

When a feature is loaded one of the top-level forms evaluated is a call to
the @code{provide} function. This names the feature and installs it into
the list of present features.

@defvar features
A list of the features currently present (that is, loaded) in the
current module. Each feature is represented by a symbol. Usually the
print name of the symbol (the name of the feature) is the same as the
name of the file it was loaded from, minus any @samp{.jl} or
@samp{.jlc} suffix.

@lisp
features
    @result{} (info isearch fill-mode texinfo-mode lisp-mode xc)
@end lisp
@end defvar

@defun featurep feature
Returns true if the feature @var{feature} has been loaded
into the current module.
@end defun

@defun provide feature
Adds @var{feature} (a symbol) to the list of loaded features. A call
to this function is normally one of the top-level forms in a file.

@lisp
;;;; maths.jl -- the @code{maths} library

(provide 'maths)
@dots{}
@end lisp
@end defun

@defun require feature @t{#!optional} file
Show that the caller is planning to use the feature @var{feature} (a symbol).
This function will check the @code{features} variable to see if @var{feature}
is already loaded, if so it will return immediately.

If @var{feature} is not present it will be loaded. If @var{file} is
given it specifies the first argument to the @code{load} function, else
the print name of the symbol @var{feature} is used, with any @samp{.}
characters replaced by the operating system's directory separator
(@pxref{Module Loading}).

@lisp
;;;; physics.jl -- the @code{physics} library

(require 'maths)                ;Need the @code{maths} library
(provide 'physics)
@dots{}
@end lisp

When called interactively the symbol @var{feature} is prompted for.
@end defun

Features may also be provided by modules, for more details @xref{Module
Loading}.


@node Compiled Lisp, Datums, Loading, The language
@section Compiled Lisp
@cindex Compiled Lisp

@code{librep} contains a Lisp compiler as well as an interpreter; this
takes a Lisp form or program and compiles it into a @dfn{byte-code}
object. This byte-code object is a string of characters representing
virtual machine instructions, a vector of constants and some other
meta-information. The system also contains a byte-code interpreter;
this takes the compiled byte-codes and executes them by simulating the
virtual machine. This simulation will have exactly the same effect as
interpreting the original form or program.

One of the main reasons for compiling programs is to increase their
efficiency. Compiled functions are likely to be more efficient than
interpreted counterparts in all areas (space and time). For example:

@example
user> (define (fib n) (if (<= n 2) 1 (+ (fib (- n 1)) (fib (- n 2)))))
user> ,time (fib 30)
832040
Elapsed: 17.05572 seconds
user> ,compile
user> ,time (fib 30)
832040
Elapsed: 1.479007 seconds
@end example

@noindent
---the compiled function is over an order of magnitude faster than the
interpreted version.

@menu
* Compilation Functions::       How to compile Lisp programs
* Compiler Declarations::       Hinting to the compiler
* Compilation Tips::            Getting the most out of the compiler
* Disassembly::                 Examining compiled functions
@end menu


@node Compilation Functions, Compiler Declarations, , Compiled Lisp
@subsection Compilation Functions
@cindex Compilation functions
@cindex Functions, compilation

@defun compile-form form
This function compiles the Lisp form @var{form} into a byte-code form
which is returned.

@lisp
(compile-form '(setq foo bar))
    @result{} (run-byte-code "F!" [bar foo] 2)
@end lisp
@end defun

@deffn Command compile-function function
This function replaces the uncompiled body of the function @var{function}
(a symbol) with a compiled version, then returns @var{function}.
@end deffn

@deffn Command compile-file file-name
This function compiles the file called @var{file-name} into a file of
compiled Lisp forms whose name is @var{file-name} with @samp{c} appended
to it (i.e. if @var{file-name} is @file{foo.jl} it will be compiled to
@file{foo.jlc}).

If an error occurs while the file is being compiled any semi-written
file will be deleted.

When called interactively this function will ask for the value of
@var{file-name}.
@end deffn

@deffn Command compile-directory directory @t{#!optional} force exclude
Compiles all the Lisp files in the directory called @var{directory} which
either haven't been compiled or whose compiled version is older than
the source file (Lisp files are those ending in @samp{.jl}).

If the optional argument @var{force} is true @emph{all} Lisp files
will be recompiled whatever the status of their compiled version.

The @var{exclude} argument may be a list of filenames, these files will
@emph{not} be compiled.

When this function is called interactively it prompts for the directory.
@end deffn

@deffn Command compile-module module-name
Compiles all uncompiled function definitions in the module named
@var{module-name} (a symbol).

When called interactively the module name will be prompted for.
@end deffn

@defun run-byte-code byte-codes constants stack
Interprets the string of byte instructions @var{byte-codes} with
the vector of constants @var{constants}.

This function should @emph{never} be called by hand. The compiler will
produce calls to this function when it compiles a form or a function.
@end defun

There is a second form that byte-code objects can take: a vector whose
read syntax includes a preceding @samp{#} character is a @dfn{byte-code
subr}. These objects represent compiled Lisp functions and macros.

@defun bytecodep arg
Returns true if @var{arg} is a byte-code subroutine.
@end defun


@node Compiler Declarations, Compilation Tips, Compilation Functions, Compiled Lisp
@subsection Compiler Declarations
@cindex Compiler declarations
@cindex Declarations, compiler

It is often useful to be able to give the compiler extra knowledge
about the program forms that it is compiling. The language includes
special declaration forms that have no effect when interpreted, but are
meaningful to the compiler as it traverses the program.

@defmac declare clause@dots{}
Offer the information contained in the @var{clause}@dots{} forms to the
compiler, which it may or may not use when compiling the program.

Each @var{clause} is a list, the first element of each clause is a
symbol defining the type of declaration, the interpretation of any
other elements in the clause depends upon the declaration type.

The following table lists the syntax of all currently supported
declaration types:

@table @code
@item (bound @var{variables}@dots{})
This declaration tells the compiler that all symbols @var{variables}
have lexical bindings for the extent of the current lexical scope. This
is often useful to prevent spurious compiler warnings.

@item (special @var{variables}@dots{})
This tells the compiler that all symbols @var{variables} have special
(dynamic) bindings for the extent of the current lexical scope.

(It is important that the compiler is able to distinguish special
bindings from lexical bindings, since different instruction sequences
must be generated to access the different types of binding.)

@item (unused @var{variables}@dots{})
Directs the compiler not to warn about bindings for
@var{variables}@dots{} being unreferenced.

@item (inline @var{names}@dots{})
Tells the compiler that it should consider inlining calls to the
functions called @var{names}@dots{}. Inlining will only occur if these
functions are declared in the same module as, and after, the
declaration itself.

@item (in-module @var{module-name})
This declaration should occur at the top-level of a program; it tells
the compiler that the forms in the program will be evaluated within the
context of the module called @var{module-name} (a symbol).

@item (language @var{module})
Explicitly specifies the particular language dialect that the current
module or file body is written for. Language dialects included with the
librep distribution include @code{rep}, @code{scheme} and
@code{unscheme}. These are also the names of the modules that should be
imported to use a particular dialect.

By default, the @code{rep} dialect is assumed for code outside module
definitions. For code inside a module definition the list of imported
modules is scanned for a known language dialect (i.e. if the module
imports @code{rep}, then the rep language dialect is compiled for).

@item (unsafe-for-call/cc)
Tell the compiler that it may register-allocate variables, even if it
can't prove that doing so wouldn't produce incorrect results if
@code{call/cc} causes a function call to return more than once
(@pxref{Continuations}). This declaration applies to the entire file
that it occurs in.

Without this declaration, the compiler will only register-allocate
bindings if the following conditions are met:

@itemize @bullet
@item the binding is not accessed from any inner closures, and,

@item the binding is never modified after being initialized (actually,
the binding may be modified between being intialized and the next
function call)
@end itemize

@noindent
this declaration is often useful where @code{call/cc} isn't used, and
there is a lot of side effecting of local variables.
@end table

Declaration forms always evaluate to false.
@end defmac

A second type of declaration is the @code{eval-when-compile} form, it
allows Lisp forms to be evaluated only at compile-time.

@defmac eval-when-compile form
This form tells the system that @var{form} should only be evaluated
when the containing code is being compiled.

The compiler knows to recognize @var{form}s of the pattern
@code{(eval-when-compile (require '@var{feature}))} as marking that
@var{feature} should be imported at compile-time. Any other @var{form}s
are simply evaluated in an unspecified environment.

When interpreted, @code{eval-when-compile} forms alway evaluate to
false, when compiled they evaluate to the result of evaluating
the @var{form} at compile-time.
@end defmac


@node Compilation Tips, Disassembly, Compiler Declarations, Compiled Lisp
@subsection Compilation Tips
@cindex Compilation tips
@cindex Tips, compilation

Here are some tips for making compiled code run fast(er):

@itemize @bullet
@item
Instead of using @code{while} loops to traverse lists, use @code{mapc}
or tail recursion.

For example you might code a function to scan a list using iteration
through a @code{while} loop:

@lisp
(defun scan-list (lst elt)
  "Search the LST for an element similar to ELT.
Return it if one is found."
  (catch 'return
    (while (consp lst)
      (when (equal (car lst) elt)
        (throw 'return elt))
      (setq lst (cdr lst)))))
@end lisp

@noindent
As well as obscuring what is actually happening, this will probably be
fairly slow to execute. A more elegant solution is to use
tail-recursion:

@lisp
(defun scan-list (lst elt)
  (if (equal (car lst) elt)
      elt
    (scan-list (cdr lst) elt)))
@end lisp

@noindent
An alternative idiom is to map an anonymous function over the list
using the @code{mapc} function:

@lisp
(defun scan-list (lst elt)
  (catch 'return
    (mapc (lambda (x)
            (when (equal x elt)
              (throw 'return elt)))
          lst)
    nil))
@end lisp

@noindent
In fact, the compiler knows that calls to @code{mapc} with a constant
lambda expression can be open-coded, so it will code the list traversal
directly using the virtual machine stack.

However, in most cases the execution time differences are likely to
negligible.


@item
In some cases the functions @code{member}, @code{memq}, @code{assoc},
etc@dots{} can be used to search lists. Since these are primitives
written in C they will probably execute several times faster than an
equivalent Lisp function.

So the above @code{scan-list} example can again be rewritten, this time
as:

@lisp
(defun scan-list (lst elt)
  (car (member elt lst)))
@end lisp

@item
All conditional structures are equivalent when compiled (they are all
translated to @code{cond} statements), so use whichever is the easiest
to understand.

@item
A certain amount of constant folding is performed. If a function is
known to be free of side effects, and all its arguments are constants,
then it is evaluated at compile-time, and the result folded into the
program in its place. For example

@lisp
(logor (lsh 1 6) x)
    @expansion{} (logor 32 x)
@end lisp

@item
Careful use of named constants (@pxref{Defining Variables}) can increase
the speed of some programs. For example, in the Lisp compiler itself
all the opcode values (small integers) are defined as constants.

It must be stressed that in some cases constants may @emph{not} be
suitable; they may drastically increase the size of the compiled
program (when the constants are `big' objects, i.e. long lists) or even
introduce subtle bugs (since two references to the same constant may
not be @code{eq} whereas two references to the same variable are always
@code{eq}).

@item
Many primitives have corresponding byte-code instructions; these primitives
will be quicker to call than those that don't (and incur a normal function
call). Currently, the functions which have byte-code instructions (apart
from all the special forms) are:

@code{cons}, @code{car}, @code{cdr}, @code{rplaca}, @code{rplacd},
@code{nth}, @code{nthcdr}, @code{aset}, @code{aref}, @code{length},
@code{eval}, @code{+}, @code{*}, @code{/}, @code{%}, @code{mod},
@code{lognot}, @code{not}, @code{logior}, @code{logand}, @code{logxor},
@code{equal}, @code{eq}, @code{=}, @code{/=}, @code{>}, @code{<},
@code{>=}, @code{<=}, @code{1+}, @code{1-}, @code{-}, @code{set},
@code{lsh}, @code{zerop}, @code{null}, @code{atom}, @code{consp},
@code{listp}, @code{numberp}, @code{stringp}, @code{vectorp},
@code{throw}, @code{boundp}, @code{symbolp}, @code{get}, @code{put},
@code{signal}, @code{return}, @code{reverse}, @code{nreverse},
@code{assoc}, @code{assq}, @code{rassoc}, @code{rassq}, @code{last},
@code{mapcar}, @code{mapc}, @code{member}, @code{memq}, @code{delete},
@code{delq}, @code{delete-if}, @code{delete-if-not},
@code{copy-sequence}, @code{sequencep}, @code{functionp},
@code{special-form-p}, @code{subrp}, @code{eql}, @code{max},
@code{min}, @code{filter}, @code{macrop}, @code{bytecodep},
@code{bind-object}.

@item
When a file is being compiled each top-level form it contains is inspected
to see if it should be compiled into a byte-code form. Different types
of form are processed in different ways:

@itemize @bullet
@item
Function and macro definitions have their body forms compiled into a single
byte-code form. The doc-string and interactive declaration are not compiled.

@item
If the form is a list form (@pxref{List Forms}) and the symbol which is
the car of the list is one of:

@code{if}, @code{cond}, @code{when}, @code{unless}, @code{let}, @code{let*},
@code{catch}, @code{unwind-protect}, @code{error-protect}, @code{with-buffer},
@code{with-window}, @code{progn}, @code{prog1}, @code{prog2}, @code{while},
@code{and}, @code{or}, @code{case}.

@noindent
then the form is compiled. Otherwise it is just written to the output file
in its uncompiled state.
@end itemize

If your program contains a lot of top-level forms which you know will
not be compiled automatically, consider putting them in a @code{progn}
block to make the compiler coalesce them into one byte-code form.
@end itemize


@node Disassembly, , Compilation Tips, Compiled Lisp
@subsection Disassembly
@cindex Disassembly
@cindex Compilation, disassembly of forms

It is possible to disassemble byte-code forms; originally this was so I
could figure out why the compiler wasn't working but if you're curious
about how the compiler compiles a form it may be of use to you.

Naturally, the output of the disassembler is a listing in the assembly
language of the @code{librep} virtual machine---it won't take a
byte-code form and produce the equivalent Lisp code!

@deffn Command disassemble-fun function @t{#!optional} stream
This function disassembles the compile Lisp function @var{function}. It
writes a listing to the output stream @var{stream} (normally the
value of the @code{standard-output} variable).

When called interactively it will prompt for a function to disassemble.
@end deffn

When reading the output of the disassembler bear in mind that
@code{librep} simulates a stack machine for the code to run on. All
calculations are performed on the stack, the value left on the stack
when the piece of code ends is the value of the byte-code form.

Here is a small example. Consider the @code{fib} function given at the
start of this section:

@lisp
(define (fib n)
  (if (<= n 2)
      1
    (+ (fib (- n 1))
       (fib (- n 2)))))
@end lisp

@noindent
After compilation and disassembly, the following is produced (but
without the annotations):

@example
Disassembly of #<closure fib>:

21 bytes, 1 constants, and (5,0,1) stack slots

0    required-arg       ;requires a single parameter
1    dup
2    slot-set #0        ;store it in register 0 (r0)
3    pushi 2
4    le
5    jn 10              ;unless r0 <= 2, goto 10
8    pushi 1
9    return             ;else, return 1
10   refg [0] fib
11   slot-ref #0
12   dec
13   call #1            ;push result of (fib (1- n))
14   refg [0] fib
15   slot-ref #0
16   pushi 2
17   sub
18   call #1            ;push (fib (- n 2))
19   add
20   return             ;return the sum of the two calls
@end example


@node Datums, Queues, Compiled Lisp, The language
@section Datums
@cindex Datums
@cindex Data types, datums

@dfn{Datums} are the mechanism by which @code{librep} allows Lisp
programs to define new data types, such that these types are completely
distinct from the built-in data types (i.e. they match none of the
standard type predicates).

They also provide encapsulation, in that the data objects they provide
are completely opaque, unless a pre-defined value is known (which was
specified when the object was created, and is typically known only by
the object's creator).

@defun make-datum value key
Create and return a new datum object. It has the value @var{value}
associated with it, and has type @var{key}.
@end defun

@defun datum-ref arg key
If @var{arg} has type @var{key}, then return the value associated with
it. Otherwise, an error is signalled.
@end defun

@defun datum-set arg key value
If @var{arg} has type @var{key}, then set the value associated with it
to be @var{value}. Otherwise, an error is signalled.
@end defun

@defun has-type-p arg key
Return true if @var{arg} has type @var{key}.
@end defun

@defun define-datum-printer key printer
Associate the function @var{printer} with all datum objects of type
@var{key}. When any such object is printed, @var{printer} is applied to
two arguments, the datum and the stream to which it should be printed
(@pxref{Output Streams}).
@end defun


@node Queues, Records, Datums, The language
@section Queues
@cindex Queues
@cindex Data types, queues

A @dfn{queue} is an ordered set of objects, such that objects enter at
one end of the queue (the @dfn{tail}), and leave from the other end of
the queue (the @dfn{head}). The acts of entering and leaving a queue
are often called @dfn{enqueing} and @dfn{dequeueing}.

@code{librep} provides a straightforward queue implementation,
implemented by the @code{rep.data.queues} module (@pxref{Modules}).

@defun make-queue
Create and return a new queue object. The queue will initially be
empty.
@end defun

@defun enqueue q arg
Add the object @var{ARG} to the tail of the queue @var{q}.
@end defun

@defun dequeue q
Remove the object at the head of the queue @var{q}, and return it. If
@var{q} is empty, an error is signalled.
@end defun

@defun queue-empty-p q
Return true if the queue @var{q} is not empty.
@end defun

@defun queuep arg
Return true if the object @var{arg} is a queue.
@end defun

@defun queue->list q
Return a list of objects representing the contents of the queue
@var{q}, with objects ordered from head to tail. Modifying the list
structure causes undefined effects to the queue itself.
@end defun

@defun queue-length q
Return the number of objects stored in the queue @var{q}.
@end defun

@defun delete-from-queue q arg
Removes any occurrences of the object @var{arg} from the queue @var{q}.
@end defun


@node Records, Hash Tables, Queues, The language
@section Records
@cindex Records
@cindex Data types, records

@code{librep} provides a convenient means of defining structured data
types, these types are known as @dfn{records}. Each record is a
distinct data type, meaning that there will only be a single
type-predicate matching objects of any individual record type.

All definitions documented in this section are provided by the
@code{rep.data.records} module (@pxref{Modules}).

Record types are defined using the @code{define-record-type} macro,
this in turn defines a number of functions implementing the type. These
functions include a constructor, a type predicate, and a user-defined
set of field-accessor and -modifier functions.

@defmac define-record-type type (constructor fields@dots{}) [predicate] (field accessor [modifier])@dots{}

This macro creates a new record type storing an opaque object
identifying the type in the variable named @var{type}.

It then defines a function @var{constructor} with parameter list as
specified by the @var{fields@dots{}}, and a predicate function called
@var{predicate} if @var{predicate} is given.

The fields of the record are defined by the sequence of
@code{(@var{field} @var{accessor} [@var{modifier}])} forms, each form
describes a single field (named @var{field}, which may match one of the
constructor arguments).

For each field a function @var{accessor} will be defined that when
applied to an argument of the record type, returns the value stored in
the associated @var{field}. If the @var{modifier} name is defined a
function will be defined of that name, that when applied to a record
and an object, stores the object into the associated field of the
record.

Note that the @var{fields@dots{}} may include all the standard
lambda-list features (@pxref{Lambda Expressions}), including keyword
parameters and default values.
@end defmac

Here is an example record definition:

@lisp
(define-record-type :pare
  (kons x y)                         ; constructor
  pare?                              ; predicate
  (x kar set-kar!)                   ; fields w/ optional accessors
  (y kdr))                           ;and modifiers
@end lisp

@noindent
the variable @code{:pare} is bound to the record type. Following this
definition, the record type could be used as follows:

@lisp
(define x (kons 1 2))

(pare? x)
    @result{} t

(kar x)
    @result{} 1

(set-kar! x 42)

(kar x)
    @result{} 42
@end lisp

By default record objects print as the name of their type in angle
brackets, e.g. for the above @code{pare} type, each object would print
as the string @samp{#<:pare>}. This may be redefined using the
@code{define-record-discloser} function.

@defun define-record-discloser type discloser
Associate the function @var{discloser} with the record type @var{type}.
When any record of this type is printed, @var{discloser} is applied to
the object, it should return the value that will actually be printed.
@end defun

For the above example, the following could be used:

@lisp
(define-record-discloser :pare (lambda (x) `(pare ,(kar x) ,(kdr x))))

(kons 'a 'b)
    @result{} (pare a b)
@end lisp

Constructors for records with large numbers of fields often benefit
from using keyword parameters. For example the @code{kons} record above
could be defined as follows (though this would make more sense if it
had more than two fields):

@example
(define-record-type :pare
  (kons #!key (kar 1) (kdr 2))
  pare?
  (kar kar set-kar!)
  (kdr kdr set-kdr!))

(kons #:kar 42) @result{} (pare 42 2)
(kons #:kdr 42) @result{} (pare 1 42)
@end example


@node Hash Tables, Guardians, Records, The language
@section Hash Tables
@cindex Hash tables
@cindex Data types, hash tables

The @code{rep.data.tables} module provides a flexible hash table
implementation (@pxref{Modules}). Each hash table is represented by a
lisp object satisfying the @code{tablep} predicate:

@defun tablep arg
Return true if @var{arg} is a hash table.
@end defun

Hash tables may be created by using the @code{make-table} and
@code{make-weak-table} functions:

@defun make-table hash-fun compare-fun
Create and return a new hash table. When storing and referencing keys
it will use the function @var{hash-fun} to map keys to hash codes
(positive fixnums), and the predicate function @var{compare-fun} to
compare two keys (should return true if the keys are considered equal).
@end defun

@defun make-weak-table hash-fun compare-fun
Similar to @code{make-table}, except that key-value pairs stored in the
table are said to be ``weakly keyed''. That is, they are only retained
in the table as long the key has not been garbage collected.

Unlike with tables created by the @code{make-table} function, the fact
that the key is stored in the table is not considered good enough to
prevent it being garbage collected.
@end defun

@defun table-ref table key
Return the value stored in hash table @var{table} indexed by object
@var{key}. Returns false if no such value exists.
@end defun

@defun table-bound-p table key
Returns true if the hash table @var{table} contains a value associated
with @var{key}.
@end defun

@defun table-set table key value
Associate the value @var{value} with @var{key} in hash table
@var{table}. Returns @code{value}.
@end defun

@defun table-unset table key
Remove any value stored in @var{table} associated with @var{key}.
@end defun

@defun table-walk function table
Call function @var{function} for every key-value pair stored in hash
table @var{table}. For each pair, the function is called with arguments
@code{(@var{key} @var{value})}.
@end defun

Several hash functions are also provided:

@defun string-hash string
Return an integer representing the string @var{string}.
@end defun

@defun symbol-hash symbol
Call @code{(string-hash (symbol-name @var{symbol}))}.
@end defun

@defun eq-hash arg
Return a hash value representing object @var{arg}. The hash is
generated from the @emph{address} of the object.
@end defun

@defun equal-hash arg
Return a hash value representing object @var{arg}. The hash is
generated from the @emph{contents} of the object.
@end defun


@node Guardians, Streams, Hash Tables, The language
@section Guardians
@cindex Guardians
@cindex Garbage collection, guardians

A @dfn{guardian} is a lisp object used to control when other data
objects are recycled by the garbage collector (@pxref{Garbage
Collection}).@footnote{Guardians were first described in a paper by R.
Kent Dybvig, Carl Bruggeman, and David Eby: @cite{"Guardians in a
Generation-Based Garbage Collector", ACM SIGPLAN Conference on
Programming Language Design and Implementation, June 1993.}} The usual
behaviour of the collector is to recycle objects as soon as they have
no remaining references.

Guardians allow the programmer to detect when a specified object would
be freed by the garbage collector, and to implement their own
allocation policy. This can be useful, for example, with objects that
have a high creation-overhead, and thus need to be cached for
performance reasons.

@defun make-guardian
This function allocates and returns a new guardian. Each guardian has a
list of data objects associated with it; some of which may have been
proved to have no remaining references to them (except from the
guardian system).

Calling the guardian object with a single argument, adds that value to
the list of objects associated with that guardian. Calling the guardian
with no arguments has one of two effects:

@itemize @bullet
@item
If objects are associated with the guardian that have been proved to be
inaccessible, then return one of those objects, and remove it from the
list of objects associated with the guardian.

@item
If none of the associated objects have been proved to be inaccessible,
then return the value false.
@end itemize
@end defun

Note the use of the word ``prove'' in the above description, objects
are only moved into a guardian's inaccessible set by the garbage
collector.

Here is an example use of the guardian system:

@lisp
;; create a new guardian object
(setq G (make-guardian))

;; create a lisp object
(setq x (cons 'a 'b))
   @result{} (a . b)

;; protect the object using the guardian
(G x)

;; remove the sole reference to the object
(setq x nil)
   @result{} ()

;; invoke the garbage collector, this will
;; prove that the value added to the
;; guardian is no longer accessible
(garbage-collect)

;; call the guardian to retrieve the
;; inaccessible value
(G)
   @result{} (a . b)

;; no more inaccessible values available
(G)
   @result{} ()
@end lisp


@node Streams, Hooks, Guardians, The language
@section Streams
@cindex Streams
@cindex Input and output

A @dfn{stream} is a Lisp object which is either a data sink (an
@dfn{output stream}) or a data source (an @dfn{input stream}). All
streams produce or consume sequences of 8-bit characters.

Streams are very flexible, functions using streams for their input and
output do not need to know the type of stream being accessed. For
example the Lisp reader (the @code{read} function) takes an input
stream as its sole argument, it then reads characters from this stream
until it has parsed a whole object. This stream could be a file, a
function, or even a string; the @code{read} function does not need to
differentiate.

@defun streamp arg
Return true if @var{arg} is a stream.
@end defun

@defun input-stream-p arg
Return true if @var{arg} is an input stream.
@end defun

@defun output-stream-p arg
Return true if @var{arg} is an output stream.
@end defun

@menu
* Input Streams::               Types of input stream
* Output Streams::              Types of output stream
* Input Functions::             Functions to read from streams
* Output Functions::            How to output to a stream
* Formatted Output::            Output by template
@end menu


@node Input Streams, Output Streams, , Streams
@subsection Input Streams
@cindex Input streams
@cindex Streams, input

These are the possible types of input stream, for the functions which
use them see @ref{Input Functions}.

@table @code
@item @var{file}
Characters are read from the file object @var{file}, for the functions
which manipulate file objects see @ref{Files}.

@item @var{function}
Each time an input character is required the @var{function} is called with
no arguments. It should return the character read (an integer) or false
if for some reason no character is available.

@var{function} should also be able to `unread' one character. When this
happens the function will be called with one argument---the value of
the last character read. The function should arrange it so that the
next time it is called it returns this character. A possible implementation
could be,

@lisp
(defvar ms-unread-char nil
  "If true the character which was pushed back.")

(defun my-stream (#!optional unread-char)
  (if unread-char
      (setq ms-unread-char unread-char)
    (if ms-unread-char
        (prog1
          ms-unread-char
          (setq ms-unread-char nil))
      ;; Normal case -- read and return a character from somewhere
      @dots{}
@end lisp

@item nil
Read from the stream stored in the variable @code{standard-input}.
@end table

It is also possible to use a string as an input stream. The string to
be read from must be applied to the @code{make-string-input-stream} function
and the result from this function used as the input stream.

@defun make-string-input-stream string @t{#!optional} start
Returns an input stream which will supply the characters of the string
@var{string} in order starting with the character at position @var{start}
(or from position zero if this argument is undefined).

@lisp
(read (make-string-input-stream "(1 . 2)"))
    @result{} (1 . 2)
@end lisp
@end defun

@defvar standard-input
The input stream which is used when no other is specified or is false.
@end defvar

Applications that embed @code{librep}, or dynamically loaded
extensions, may provide further input stream types.


@node Output Streams, Input Functions, Input Streams, Streams
@subsection Output Streams
@cindex Output streams
@cindex Streams, output

These are the different types of output stream, for the functions which
use them see @ref{Output Functions}.

@table @code
@item @var{file}
Writes to the file object @var{file}. @xref{Files}.

@item @var{function}
The function @var{function} is called with one argument, either a string
or a character. This should be used as the circumstances dictate. If the
function returns a number it is the number of characters actually used,
otherwise it is assumed that all the characters were successful.

@item @var{process}
Writes to the standard input of the process object @var{process}. If
@var{process} isn't running an error is signalled. @xref{Processes}. 

@item t
Appends the character(s) to the end of the status line message.

@item ()
Write to the stream stored in the variable @code{standard-output}.
@end table

It is also possible to store the characters sent to an output stream
in a string.

@defun make-string-output-stream
Returns an output stream. It accumulates the text sent to it for the benefit
of the @code{get-output-stream-string} function.
@end defun

@defun get-output-stream-string string-output-stream
Returns a string consisting of the text sent to the @var{string-output-stream}
since the last call to @var{get-output-stream-string} (or since this stream
was created by @code{make-string-output-stream}).

@lisp
(setq stream (make-string-output-stream))
    @result{} ("" . 0)
(prin1 keymap-path stream)
    @result{} ("(lisp-mode-keymap global-keymap)" . 64)
(get-output-stream-string stream)
    @result{} "(lisp-mode-keymap global-keymap)"
@end lisp
@end defun

@defvar standard-output
This variable contains the output stream which is used when no other
is specified (or when the given output stream is false).
@end defvar

@defvar standard-error
This variable contains the output stream which is used when an error
message is being reported.
@end defvar

Applications that embed @code{librep}, or dynamically loaded
extensions, may provide further output stream types.


@node Input Functions, Output Functions, Output Streams, Streams
@subsection Input Functions
@cindex Input functions
@cindex Functions, input
@cindex Streams, input functions

@defun read-char stream
Read and return the next character from the input stream @var{stream}. If
the end of the stream is reached false is returned.
@end defun

@defun read-line stream
This function reads one line of text from the input stream
@var{stream}, a string containing the line (including the newline
character which terminates the line).

If the end of stream is reached before any characters can be read
false is returned, if the end of stream is reached but some
characters have been read (but not the newline) these characters are
made into a string and returned.

Note that unlike the Common Lisp function of the same name, the newline
character is not removed from the returned string.
@end defun

@defun read stream
This function is the function which encapsulates the Lisp reader
(@pxref{The Lisp Reader}). It reads as many characters from the input
stream @var{stream} as required to form the read syntax of a single
Lisp object (@pxref{Read Syntax}), this object is then returned.
@end defun

@defun read-from-string string @t{#!optional} start
Reads one Lisp object from the string @var{string}, the first character
is read from position @var{start} (or position zero).

@lisp
(read-from-string @var{string} @var{start})
@equiv{}
(read (make-string-input-stream @var{string} @var{start}))
@end lisp
@end defun


@node Output Functions, Formatted Output, Input Functions, Streams
@subsection Output Functions
@cindex Output functions
@cindex Functions, output
@cindex Streams, output functions

@defun write stream data @t{#!optional} length
Writes the specified character(s) to the output stream @var{stream}.
@var{data} is either the character or the string to be written. If
@var{data} is a string the optional argument @var{length} may
specify how many characters are to be written. The value returned
is the number of characters successfully written.

@lisp
(write standard-output "Testing 1.. 2.. 3..")
    @print{} Testing 1.. 2.. 3..
    @result{} 19
@end lisp
@end defun

@defun copy-stream input-stream output-stream
This function copies all characters which may be read from
@var{input-stream} to @var{output-stream}. The copying process is not
stopped until the end of the input stream is read. Returns the number
of characters copied.

Be warned, if you don't choose the streams carefully you may get a
deadlock which only an interrupt signal can break!
@end defun

@defun print object @t{#!optional} stream
Outputs a newline character to the output stream @var{stream}, then
writes a textual representation of @var{object} to the stream.

If possible, this representation will be the read syntax of
@var{object}.

@var{object} is returned.

@lisp
(print '(1 2 3))
    @print{}
    @print{} (1 2 3)
    @result{} (1 2 3)
@end lisp
@end defun

@defun prin1 object @t{#!optional} stream
Similar to @code{print} but no initial newline is output.

@lisp
(prin1 '(1 2 3))
    @print{} (1 2 3)
    @result{} (1 2 3)

(prin1 '|(xy((z]|)              ;A strange symbol
    @print{} \(xy\(\(z\]
    @result{} \(xy\(\(z\]
@end lisp
@end defun

@defun prin1-to-string object
Returns a string containing the characters that @code{prin1} would
output when it prints @var{object}.

@lisp
(prin1-to-string '(1 2 3))
    @result{} "(1 2 3)"
@end lisp
@end defun

@defun princ object @t{#!optional} stream
Prints a textual representation of @var{object} to the output stream
@var{stream}. No steps are taken to create output that @code{read} can
parse; in particular, no double-quote characters surround strings.

@lisp
(princ "foo")
    @print{} foo
    @result{} "foo"

(princ '|(xy((z]|)
    @print{} (xy((z]
    @result{} \(xy\(\(z\]
@end lisp
@end defun

Several variables may be used to control how objects are printed.

@defvar print-escape
This defines which control characters @code{print} and @code{prin1}
will escape (using backslashes). Possible values are:

@table @code
@item ()
Only escape double-quote and backslash characters.

@item newlines
Only escape double-quote, backslash, newline, @kbd{TAB}, and formfeed
characters.

@item t
Escape double-quote, backslash, and all control characters (anything
with a numeric value less than 32, or greater than 126).
@end table
@end defvar

@defvar print-length
This variable, if true, limits the number of elements printed
from lists.
@end defvar

@defvar print-level
This variable, if true, limits the recursion depth when
printing lists.
@end defvar


@node Formatted Output, , Output Functions, Streams
@subsection Formatted Output
@cindex Formatted output
@cindex Output, formatted
@cindex Streams, formatted output

@defun format stream template @t{#!rest} values
Writes to a stream, @var{stream}, a string constructed from the
format string, @var{template}, and list of arguments @var{values}.

If @var{stream} is false the resulting string will be returned,
not written to a stream.

@var{template} is a template for the output string, any @samp{%}
characters introduce a substitution, using the next unused argument.
The substitutions have the following syntax,

@example
%[@var{index}$][@var{flags}][@var{field-width}]@var{conversion}
@end example

@noindent
@var{index} is an optional decimal number specifying exactly which of
the @var{values} this conversion refers to (with the first at position
one), and is usually used when translating messages; by default the
next value is used.

@var{field-width} is a positive decimal integer, defining the size in
characters of the substitution output.

@var{conversion} is a character defining how to convert the
corresponding argument value to text. The default options are:

@table @samp
@item s
Write the printed representation of the value without quoting (as if from
the @code{princ} function).

@item S
Write the printed representation @emph{with} quoting enabled (like the
@code{prin1} function).

@item d
Output the value as a decimal number.

@item o
Write the value in octal.

@item x
@itemx X
In hexadecimal.

@item c
Write the character specified by the value.

@item %
Print a literal percent character. None of the @var{values} are used.
@end table

@var{flags} is a sequence of zero or more of the following characters,

@table @asis
@item @samp{_}
Left justify the substitution within the field.

@item @samp{^}
Truncate the substitution at the size of the field.

@item @samp{0}
Pad the field with zeros instead of spaces.

@item @samp{+}
For @samp{d}, @samp{x}, and @samp{o} conversions, output a leading plus
sign if the argument is positive.

@item @samp{ } (a space)
For @samp{d}, @samp{x}, and @samp{o} conversions, if the result doesn't
start with a plus or minus sign, output a leading space.
@end table

The list of @var{conversions} can be extended through the
@code{format-hooks-alist} variable; the strings created by these extra
conversions are formatted as if by the `s' conversion.

Note that the @var{field-width} and all flags currently have no effect
on the @samp{S} conversion, (or the @samp{s} conversion when the
argument isn't a string).

If @var{stream} isn't false (in which case the created string is
returned) the value of @var{stream} is returned.

@lisp
(format nil "foo %S bar 0x%x" '(x . y) 255)
    @result{} "foo (x . y) bar 0xff"

(format standard-output "The %2$s is %1$s!" "purple" "dog")
    @print{} The dog is purple!
    @result{} #<buffer *jade*>
@end lisp
@end defun

@defvar format-hooks-alist
This variable is an association-list, each element being
@code{(@var{char} . @var{function})}, defining extra conversions
for the @code{format} function.

If a conversion @samp{%@var{x}} is given, and the alist contains an
element whose car is the character @var{x}, the the associated function
is called with one value, the next argument to be formatted. It should
return the string to be inserted.
@end defvar


@node Hooks, Files, Streams, The language
@section Hooks
@cindex Hooks

A @dfn{hook} allows you to wedge your own pieces of Lisp code into the
operation of other functions, enable the extension of that
functionality. These pieces of code are evaluated via the hook and the
result is available to the hook's caller. One hook has already been
encountered, the @code{format-hooks-alist} variable (@pxref{Formatted
Output}).

@menu
* Functions As Hooks::          Some hooks are a single function,
* Normal Hooks::                Others may be a list of pieces of code
                                  to evaluate.
@end menu


@node Functions As Hooks, Normal Hooks, , Hooks
@subsection Functions As Hooks
@cindex Functions as hooks
@cindex Hooks, functions as

Some hooks only allow a single piece of code to be hooked in. Usually a
normally-undefined function is used; to install your hook defined a
function with the name of the hook. When the hook is to be evaluated
the function is called.

Generally the name of the hook's function will end in @code{-function}.

An alternative scheme is to use a variable to store the hook, its value
should be the function to call.


@node Normal Hooks, , Functions As Hooks, Hooks
@subsection Normal Hooks
@cindex Normal hooks
@cindex Hooks, normal

This is the standard type of hook, it is a variable whose value is a
list of functions. When the hook is evaluated each of the functions
will be called in turn.

The names of hooks of this type will normally end in @code{-hook}.

These functions are exported by the @code{rep.system} module.

@defun add-hook hook function @t{#!optional} at-end
This function adds a new function @var{function} to the list of
functions installed in the (list) hook @var{hook} (a symbol).

If @var{at-end} is true the new function is added at the end
of the hook's list of functions (and therefore will be called last when
the hook is evaluated), otherwise the new function is added to the
front of the list.

@lisp
text-mode-hook
    @result{} (#<closure fill-mode-on>)
(add-hook 'text-mode-hook my-function)
    @result{} (#<closure my-function> #<closure fill-mode-on>)
@end lisp
@end defun

@defun remove-hook hook function
This function removes the function @var{function} from the list of
functions stored in the (list) hook @var{hook} (a symbol).

@emph{All} instances of @var{function} are deleted from the hook.
@end defun

There are actually three calling conventions for this type of hook,
differing in how many of the functions in the list actually get called.
In this simplest form, @emph{all} functions are called. In an
@code{and} type hook, functions are only invoked while all others have
returned true. As soon as the first function in the hook returns
false, no others will be called. Finally, an @code{or} type hook
aborts when a function returns a true result.

@defun call-hook hook arg-list @t{#!optional} type

Call the hook named by the symbol @var{hook}, passing all functions the
arguments in the list @var{arg-list}. Note that @var{hook} may also be
the actual list of functions to call.

@var{type} defines how the return values of each function in the hook
are treated. If @var{type} is false they are ignored, if
@var{type} is the symbol @code{and} the hook aborts after a function
returns false, if @var{type} is @code{or} the hook aborts when a
function returns true.

In all cases the value returned by the last-evaluated function is
returned.
@end defun


@node Files, Processes, Hooks, The language
@section Files
@cindex Files

@code{librep} allows you to manipulate files in the operating system's
filing system; a special type of Lisp object, a @dfn{file object}, is
used to represent files which have been opened for reading or writing
(through the streams mechanism, @pxref{Streams}).

Names of files are represented by strings, the syntax of file names is
defined by the underlying operating system: @code{librep} simply treats
it as a string.

Unless otherwise stated, all functions and variables described in the
following sections are exported by the @code{rep.io.files} module.

@menu
* File Names::                  Files are named by a string
* File Objects::                Lisp objects representing files
* File Information::            Predicates on files
* Manipulating Files::          Deleting, renaming and copying files
* Manipulating Directories::    Accessing directories
* Manipulating Symlinks::       Handling symbolic links
* File Handlers::               Extending the file name-space
* Remote Files::                Accessing remote files
@end menu


@node File Names, File Objects, , Files
@subsection File Names
@cindex File names
@cindex Names of files

A @dfn{file name} is a string identifying an individual file (or
directory) in the filing system (i.e. the disk). The exact syntax of
file names depends on the operating system. There are several functions
for manipulating file names.

@defun file-name-absolute-p file-name
Returns true when @var{file-name} is not specified relative to the
current directory.
@end defun

@defun file-name-directory file-name
This function returns the directory part of the file name string
@var{file-name}. This is the substring of @var{file-name} defining the
directory containing the file.

@lisp
(file-name-directory "/tmp/foo")
    @result{} "/tmp/"

(file-name-directory "foo")
    @result{} ""

(file-name-directory "foo/bar/")
    @result{} "foo/bar/"
@end lisp
@end defun

@defun file-name-nondirectory file-name
Returns the substring of the file name @var{file-name} which is
@emph{not} the directory part.

@lisp
(file-name-nondirectory "/tmp/foo")
    @result{} "foo"

(file-name-nondirectory "foo")
    @result{} "foo"

(file-name-nondirectory "foo/bar/")
    @result{} ""
@end lisp
@end defun

@defun file-name-as-directory file-name
Returns a string through which the item in the file system named by
@var{file-name} can be referred to as a directory.

@lisp
(file-name-as-directory "./foo")
    @result{} "./foo/"

(file-name-as-directory "./foo/")
    @result{} "./foo/"
@end lisp
@end defun

@defun directory-file-name directory-name
Returns a string through which the directory named by
@var{directory-name} can be referred to as a file.

@lisp
(directory-file-name "./foo/")
    @result{} "./foo"

(directory-file-name "./foo")
    @result{} "./foo"
@end lisp
@end defun

@defun expand-file-name file-name @t{#!optional} base-dir
Expands @var{file-name} assuming that it specifies a file relative to
@var{base-dir}. If @var{base-dir} is undefined it is taken as the
current value of the @code{default-directory} variable. While expanding
the file name, any obvious simplifications will be performed (e.g. on
Unix the removal of "." and ".." where possible).

Note that the returned file name will only be absolute if one of the
following conditions is met:

@enumerate
@item
@var{base-dir} (or @code{default-directory}) is absolute,

@item
@var{file-name} is already absolute.
@end enumerate

@lisp
(expand-file-name "foo" "./bar")
    @result{} "bar/foo"
@end lisp

Note for file handler implementors: when a handler is called for the
@code{expand-file-name} operation, it will only ever receive one
argument, the already expanded file name. The only action that may be
need to be taken is to simplify the file name (e.g. removing @file{.}
and @file{..} entries or whatever).
@end defun

@defun canonical-file-name file-name
This function returns the canonical name of the file referred to by the
string @var{file-name}. The canonical name of a file is defined such
that two files can be compared simply by comparing their canonical
names; if the names match, they refer to the same file.

(Note that the opposite isn't always true, if two canonical names don't
match the files could still be the same, for example via hard links. On
most operating systems, symbolic links will be expanded where
possible.

@lisp
(canonical-file-name "foo")
    @result{} "/home/john/src/librep/man/foo"
@end lisp
@end defun

@defun local-file-name file-name
@code{librep} supports extensible file handling (@pxref{File
Handlers}), so file names may refer to files not residing in the
system's local file structure, and thus which are unavailable to other
programs.

This function returns either the absolute name of the file
@var{file-name}, if it is found in the local system, or false, if
the file does not.

@lisp
(local-file-name "foo")
    @result{} "/home/john/src/librep/man/foo"

(local-file-name "/john@@tango:foo")
    @result{} ()
@end lisp
@end defun

@defun make-temp-name
This function returns the name of a file which, when created, may be used
for temporary storage. Each time this function is called a unique name is
computed.

@lisp
(make-temp-name)
    @result{} "/tmp/00088aaa"

(make-temp-name)
    @result{} "/tmp/00088baa"
@end lisp
@end defun

@defvar default-directory
This variable names the current working directory. All relative file
names are interpreted starting from this location in the file system.
@end defvar


@node File Objects, File Information, File Names, Files
@subsection File Objects
@cindex File objects

A file object is a Lisp object which represents an open file in the
filing system. Any file object may be used as a stream (either input or
output) to access the contents of the file (@pxref{Streams}).

@defun filep object
This function returns true when its argument is a file object.
@end defun

@menu
* Creating File Objects::       Opening files
* Destroying File Objects::     Closing files
* Functions on File Objects::   Functions operating on file objects
@end menu


@node Creating File Objects, Destroying File Objects, , File Objects
@subsubsection Creating File Objects
@cindex Creating file objects
@cindex File objects, creating
@cindex Files, opening

@defun open-file file-name mode
This function opens the file called @var{file-name} (@pxref{File
Names}) and returns the new file object.

The @var{mode} argument is a symbol defining the access modes used to
open the file with, the options are:

@table @code
@item read
Open an existing file for reading only.

@item write
Open the file for writing only, if the file exists it is truncated to
zero length. Otherwise a new file is created.

@item append
Open the file for appending to, i.e. writing to the end of the file. If
the file doesn't exist it is created.
@end table
@end defun

The three standard I/O streams are also available as file handles.

@defun stdin-file
Return a file object representing the interpreters standard input.
@end defun

@defun stdout-file
Return a file object representing the interpreters standard output.
@end defun

@defun stderr-file
Return a file object representing the interpreters standard error.
@end defun

Attempting to close any of these files will result in the associated
stream being connected to @file{/dev/null}.


@node Destroying File Objects, Functions on File Objects, Creating File Objects, File Objects
@subsubsection Destroying File Objects
@cindex Destroying file objects
@cindex File objects, destroying
@cindex Files, closing

The easiest way to close a file is simply to eliminate all references to it,
subsequently the garbage collector will close it for you. It is better
to close files explicitly though since only a limited number of files may be
opened concurrently.

@defun close-file file-object
This function closes the file pointed to by the file object
@var{file-object}.

Subsequently, any stream accesses @var{file-object} are illegal and
will signal an error.
@end defun


@node Functions on File Objects, , Destroying File Objects, File Objects
@subsubsection Functions on File Objects
@cindex Functions on File Objects
@cindex File objects, functions

@defun seek-file file @t{#!optional} offset where
When called as @code{(seek-file @var{file})}, returns the distance in
bytes from the start of the file that the next character would be read
from.

When called as @code{(seek-file @var{file} @var{offset} [@var{where}])}
alters the position from which the next byte will be read. @var{where}
can be one of the values:

@table @code
@item ()
@var{offset} bytes after the current position.

@item start
@var{offset} bytes after the beginning of the file.

@item end
@var{offset} bytes before the end of the file.
@end table

Note that not all files may be seekable; if @code{(seek-file
@var{file})} returns false, indicating that the current position
is unknown, any attempts to set the current position will also fail.
@end defun

@defun flush-file file
This function flushes any buffered output to the file object
@var{file} to disk.
@end defun

@defun file-binding file
Returns the name of the file which the file object @var{file} is
currently bound to. Returns false if the file is currently unbound
(i.e. @code{close-file} was called on it).
@end defun

The next three functions are used when non-local files are being
accessed. See @ref{File Handlers} for more details.

@defun file-bound-stream file
If the file object @var{file} doesn't refer to a file in the local
filing system, return the stream that it is bound to (allowing the
file's contents to be accessed), this may or may not be another file
object.
@end defun

@defun file-handler-data file
Return the file-handler-specific data associated with the file object
@var{file}.
@end defun

@defun set-file-handler-data file data
Set the handler-specific data of file object @var{file} to @var{data}.
This should only be done by the handler owning the file.
@end defun

It's also possible to register a callback function to be invoked when
input is available on a file,

@defun set-input-handler local-file function
Arrange for @var{function} to be called whenever pending input is
available on @var{local-file}, a file object bound to a file in the
local file space.

Note that this makes @var{local-file} subsequently do non-blocking
input.

This function is normally only useful when @var{local-file} represents
a pipe or socket.
@end defun


@node File Information, Manipulating Files, File Objects, Files
@subsection File Information
@cindex File information

A number of functions exist which when given the name of a file return
one of the attributes relating to that file.

@defun file-exists-p file-name
Returns true when a file @var{file-name} exists.
@end defun

@defun file-regular-p file-name
Returns true when the file @var{file-name} is a `normal' file. This means
that it isn't a directory, device, symbolic link or whatever.
@end defun

@defun file-directory-p file-name
Returns true when the file @var{file-name} is a directory.
@end defun

@defun file-symlink-p file-name
Returns true when the file @var{file-name} is a symbolic link.
@end defun

@defun file-readable-p file-name
Returns true when the file @var{file-name} is readable.
@end defun

@defun file-writable-p file-name
Returns true when the file @var{file-name} is writable.
@end defun

@defun file-owner-p file-name
Returns true when the ownership of the file @var{file-name} is
the same as that of any files written by the editor.
@end defun

@defun file-size file-name
Returns the number of bytes stored in the file named @var{file-name}.
@end defun

@defun file-nlinks file-name
Returns the number of hard links pointing to the file @var{file-name}. If
@var{file-name} has only one name the number will be one.
@end defun

@defun file-modes file-name
This function returns the access permissions of the file @var{file-name}.
This will be an integer whose format is undefined; it differs from
operating system to operating system.
@end defun

@defun file-modes-as-string file-name
Returns a ten-character string describing the attibutes of the file
called @var{file-name}

@lisp
(file-modes-as-string ".")
    @result{} "drwxr-sr-x"
@end lisp
@end defun

@defun set-file-modes file-name modes
This function sets the access permissions of the file @var{file-name} to
the integer @var{modes} (as returned by the @code{file-modes} function).
@end defun

@defun file-modtime file-name
Returns the system time at the last modification to the file
@var{file-name}, this will be in the usual timestamp format,
@xref{Timestamps}.
@end defun

@defun file-newer-than-file-p file-name1 file-name2
This function returns true if the file @var{file-name1} was modified
more recently than the file @var{file-name2} was.
@end defun


@node Manipulating Files, Manipulating Directories, File Information, Files
@subsection Manipulating Files
@cindex Manipulating files
@cindex Files, manipulating

@deffn Command delete-file file-name
This function deletes the file called @var{file-name}. When called
interactively @var{file-name} is prompted for.
@end deffn

@deffn Command rename-file file-name new-name
This function attempts to change the name of the file @var{new-name}
to @var{new-name}.

This won't work from one file system to another or if a file called
@var{new-name} already exists, in these cases an error is signalled.

This prompts for its arguments when called interactively.
@end deffn

@deffn Command copy-file file-name destination-name
Creates a new copy of the file @var{file-name} with the name
@var{destination-name}.

The access modes of the new file will be the same as those of the original
file.

The arguments are prompted for when this function is called interactively.
@end deffn

@node Manipulating Directories, Manipulating Symlinks, Manipulating Files, Files
@subsection Manipulating Directories
@cindex Reading directories
@cindex Files, manipulating directories

@deffn Command make-directory directory-name
Create a new directory called @var{directory-name}.
@end deffn

@deffn Command delete-directory directory-name
Delete the directory called @var{directory-name}. This only succeeds if
the directory in question is empty, otherwise an error is signalled.
@end deffn

@defun directory-files directory-name
Returns a list of the names of all items in the directory whose name is
@var{directory-name}. The names in the list will be relative to the
directory @var{directory-name}.

@lisp
(directory-files "/tmp/foo"
    @result{} ("bar" "subdir" "xyz" "." "..")
@end lisp
@end defun


@node Manipulating Symlinks, File Handlers, Manipulating Directories, Files
@subsection Manipulating Symbolic Links
@cindex Manipulating Symbolic Links
@cindex Symbolic Links, manipulating

@defun make-symlink name contents
Create a symbolic link called @var{name}, containing the string
@var{contents}.
@end defun

@defun read-symlink name
Return the string that is the contents of the symbolic link called
@var{name}. Signals an error if no such link exists.
@end defun


@node File Handlers, Remote Files, Manipulating Symlinks, Files
@subsection File Handlers
@cindex File Handlers

As noted earlier, @code{librep} supports virtual files; that is it
allows file names to be accessed that don't reside on the local filing
system, or aren't normally valid as file names. This is achieved
through the use of @dfn{file handlers}, Lisp functions that have
signalled that they should be used to redirect all accesses to files
whose names match a particular regular expression (@pxref{Regular
Expressions}).

For example, there is a convention under Unix that a user's home
directory can be accessed via the file name @file{~}, even though there
is no such support from the operating system itself. So a file handler
can be (and has been) written that recognises all file names starting
with a tilde, translating them to the actual file in the file system.

@defvar file-handler-alist
This variable contains a list of file handler declarations, each one of
the form @code{(@var{regexp} . @var{function})}. Whenever a file
operation is performed on a file whose name matches @var{regexp},
@var{function} is invoked to perform the action. The function is called
as @code{(@var{function} @var{operation} @var{args}@dots{})}, where
@var{operation} and @var{args} are from the original call.

For example if the @code{file-handler-alist} contains the entry
@code{("^~" . tilde-file-handler)}, then all file operations on files
starting with a tilde are redirected to the @code{tilde-file-handler}
function.

Thus if a form @code{(file-exists-p "~/foo")} is executed, it would
result in a call to @code{tilde-file-handler} as
@code{(tilde-file-handler 'file-exists-p "~/foo")}.
@end defvar

The list of operations that may be redirected to a file handler is:
@code{file-name-absolute-p}, @code{expand-file-name},
@code{local-file-name}, @code{canonical-file-name},
@code{file-name-nondirectory}, @code{file-name-directory},
@code{file-name-as-directory}, @code{directory-file-name},
@code{open-file}, @code{close-file}, @code{flush-file},
@code{seek-file}, @code{write-buffer-contents},
@code{read-file-contents}, @code{insert-file-contents},
@code{delete-file}, @code{rename-file}, @code{copy-file},
@code{copy-file-to-local-fs}, @code{copy-file-from-local-fs},
@code{make-directory}, @code{delete-directory}, @code{file-exists-p},
@code{file-regular-p}, @code{file-readable-p}, @code{file-writable-p},
@code{file-directory-p}, @code{file-symlink-p}, @code{file-owner-p},
@code{file-nlinks}, @code{file-size}, @code{file-modes},
@code{file-modes-as-string}, @code{set-file-modes},
@code{file-modtime}, @code{directory-files},
@code{make-symlink}, @code{read-symlink}.

There are several undefined functions in this list. The
@code{write-buffer-contents}, @code{read-file-contents}, and
@code{insert-file-contents} pertain to the Jade text editor. The other
two are defined as follows.

@deffn Operation copy-file-to-local-fs file-name local-name
Called when copying files between file handlers, this operation should
copy the file matching the handler @var{file-name}, to the file on the
local file system @var{local-name}.
@end deffn

@deffn Operation copy-file-from-local-fs local-name file-name
Called when copying files between file handlers, this operation should
copy the local file @var{file-name} to the file matching the handler
@var{file-name}.
@end deffn

To prevent infinite recursion, while a particular operation is being
processed by a file handler, that operation may not be passed back to
the same handler.

To allow file handlers to handle the @code{open-file} operation, it is
possible to create file handles from arbitrary streams.

@defun make-file-from-stream file-name stream handler
Return a new file object that refers to the logical file called
@var{file-name}, that is not in the local filing system. All access to
the file object will be directed through the stream object
@var{stream}, and the file handler function @var{handler}.
@end defun

An alternative method of opening remote files is to use a temporary
file in the local file system with either one (@code{read} or
@code{write} modes), or two (@code{append} mode) synchronisations with
the remote system. This is the method used by the FTP remote file
backend (see the next section). It has the advantage of simplifying the
@code{seek-file} operation.


@node Remote Files, , File Handlers, Files
@subsection Remote files
@cindex Remote files
@cindex Files, remote
@cindex File handlers, remote files

Since one of the intentions for file handlers is to allow remote files
to be accessed, a common method of providing new methods of doing this
has been implemented, in the @file{remote.jl} Lisp library.

Accessing a file name matching the regular expression:

@example
^/(([a-zA-Z0-9._-]+)@@)?([a-zA-Z0-9._-]+):
@end example

@noindent
for example @file{/john@@host.com:file} refers to a file called
@samp{file} owned by the user @samp{john}, on the system
@samp{host.com}.

If no username is specified explicitly, two variables are used to
select the user:

@defvar remote-host-user-alist
An alist mapping host regexps to the default user name to use for
remote file connections to that host.
@end defvar

@defvar remote-default-user
User name to use for remote file connections when otherwise
unspecified. By default the current user name on the local system.
@end defvar

Two variables control how individual hosts are matched to methods of
accessing files.

@defvar remote-auto-backend-alist
An alist of @code{(@var{host-regexp} . @var{backend-type})} mapping
host names to methods of accessing remote files.
@end defvar

@defvar remote-default-backend
A symbol defining the method to use for otherwise unselected hosts.
@end defvar

A method of accessing files, or a @dfn{backend} is a symbol whose
@code{remote-backend} property names a function to call when files need
to be accessed. For example the @code{ftp} backend is initialised as:

@lisp
(put 'ftp 'remote-backend remote-ftp-handler)
@end lisp

The backend function is called as @code{(@var{function}
@var{split-name} @var{operation} @var{args})}. The @var{split-name} is
a three-element list, @code{(@var{user-or-nil} @var{host} @var{file})}
defining the file to be accessed. The other options are as usual.
Further details can be found in the @file{remote.jl},
@file{remote-ftp.jl} and @file{remote-rcp.jl} Lisp source files.

The @code{ftp} backend is currently the most well-developed, several
functions and variables may be used to customise its behaviour.

@defun remote-ftp-add-passwd user host passwd
Add the string @var{passwd} as the password for the FTP session
connecting to @var{user@@host}.
@end defun

@defvar remote-ftp-show-messages
When true (the default), messages are displayed as FTP commands are
executed.
@end defvar

@defvar remote-ftp-display-progress
When true (the default) display progress of FTP transfers.
@end defvar

@defvar remote-ftp-anon-users
A regular expression matching the user names for ``anonymous'' FTP
sessions.
@end defvar

@defvar remote-ftp-anon-passwd
The string to send as the passwd of an anonymous FTP session. By
default the current uses email address.
@end defvar

There is a problem with the @code{ftp} backend however; due to
limitations in the FTP protocol, not all @code{librep} file operations
are supported, with the most obvious exception being the
@code{make-symlink} function.

When this is a problem it may be possible to use rep's custom file
transfer protocol. If it is possible to use @code{rsh} to connect to
the remote host in question, then the @code{rep} backend may be used.

The @code{rep-remote} program distributed with @code{librep} must exist
on the remote host, this is executed via @code{rsh} and provides a
protocol for executing all of @code{librep}'s file operations on that
host. See the @file{lisp/remote-rep.jl} file in the distribution for
more details.


@node Processes, Regular Expressions, Files, The language
@section Processes
@cindex Processes
@cindex Subprocesses

When running on a Unix-style operating system @code{librep} allows you
to launch and control an arbitrary number of subprocesses. These
subprocesses can run either synchronously or asynchronously in respect
to the Lisp system; data can be sent to the @code{stdin} channel and
any output from the process is automatically written to a specified
Lisp output stream.

Unless otherwise stated, all functions and variables described in the
following sections are exported by the @code{rep.io.processes} module.

@menu
* Process Objects::             Lisp objects associated with subprocesses
* Asynchronous Processes::      Subprocesses running in parallel
* Synchronous Processes::       Subprocesses which run to completion
* Process I/O::                 Input and output with subprocesses
* Process States::              Suspending subprocesses
* Signalling Processes::        Sending signals to subprocesses
* Process Information::         Information stored in a process object
@end menu


@node Process Objects, Asynchronous Processes, , Processes
@subsection Process Objects
@cindex Process objects

A @dfn{process object} is a type of Lisp object used to provide a link
between a `physical' process running in the operating system and the
Lisp system. Each process object consists of a number of values
(references to other Lisp objects); these values are used when the
object is used to run a subprocess.

Process objects which aren't currently being used to run a subprocess
store the exit value of the last subprocess which was run on that object.

@defun processp object
This function returns true when its argument is a process object.
@end defun

The programmer-accessible components of a process object are,

@table @dfn
@item Output stream
A normal Lisp output stream (@pxref{Output Streams}), all data which the
subprocess outputs to its @code{stdout} channel is copied to this
output stream. @xref{Process I/O}.

@item Error stream
A normal Lisp output stream (@pxref{Output Streams}), all data which
the subprocess outputs to its @code{stderr} channel is copied to this
output stream. Unless explicitly specified error output goes to the
@code{stdout} stream. @xref{Process I/O}.

@item State change function
A Lisp function, called each time the state of the subprocess being run
on the object changes. @xref{Process States}.

@item Program name
The name of the program (a string) to execute when the subprocess is created.

@item Program arguments
A list of strings defining the arguments which the program executed
is given.

@item Directory
When a subprocess is started its current working directory is set to
the directory named by this component of its process object.

@item Connection type
Asynchronous subprocesses (@pxref{Asynchronous Processes}) use this
component to decide how to connect to the I/O channels of the subprocess.
Current options include pseudo-terminals and pipes.
@end table

@defun make-process @t{#!optional} output-stream state-function directory program args
This functions creates and returns a new process object. @emph{No subprocess
will be started.}

The optional arguments are used to define the values of the components of
the new process object, any undefined components will be set to default
or null values.
@end defun

For each component of a process object two functions exist; one to
read the component's value in a specific process object, the other
to set the component's value.

@defun process-prog process
Returns the value of the program name component of the process object
@var{process}.
@end defun

@defun set-process-prog process prog-name
Sets the value of the program name component of the process object
@var{process} to the string @var{prog-name}, then returns @var{prog-name}.
@end defun

@defun process-args process
Returns the value of the program arguments component of the process object
@var{process}.
@end defun

@defun set-process-args process arg-list
Sets the value of the program arguments component of the process object
@var{process} to the list @var{arg-list}, then returns @var{arg-list}.
@end defun

@defun process-dir process
Returns the value of the directory component of the process object
@var{process}.
@end defun

@defun set-process-dir process directory
Sets the value of the directory component of the process object
@var{process} to the string @var{directory}, then returns @var{directory}.
@end defun

@defvar process-environment
This is a list of environment variable definitions, as well as being
used by the @code{setenv} and @code{getenv} functions
(@pxref{Environment Variables}), it also provides the environment of
all started subprocesses.

@lisp
(car process-environment)
    @result{} "LOGNAME=john"
@end lisp
@end defvar

@defun active-processes
Returns a list containing all active (i.e. running or stopped) process
objects.
@end defun


@node Asynchronous Processes, Synchronous Processes, Process Objects, Processes
@subsection Asynchronous Processes
@cindex Asynchronous processes
@cindex Processes, asynchronous

An @dfn{asynchronous process} is one that runs in parallel with Lisp
evaluation, basically this means that once the subprocess has been
started (by the @code{start-process} function) @code{librep} will carry
on as normal.

The event loop checks for output from asynchronous processes, any found
is copied to the process' output stream, and calls the the process' state
change function when necessary (@pxref{Process States}). Alternatively
the @code{accept-process-output} function can be called to explicitly
allow output to be processed.

When using asynchronous processes you have a choice as to the Unix
mechanism used to connect the @code{stdin}, @code{stdout} and
@code{stderr} streams of the subprocess to @code{librep}'s process.

The two options currently available are pipes or pseudo-terminals; in
general pseudo-terminals should only be used to provide a direct
interface between the user and a process (i.e. the @samp{*shell*}
buffer) since they allow job control to work properly. At other times
pipes will be more efficient and are used by default. However, there
are cases where the buffering characteristics of pipes mean that ptys
must be used.

@defun start-process @t{#!optional} process program @t{#!rest} args
This function starts an asynchronous subprocess running on the process
object @var{process}. If @var{process} is undefined a new process
object is created (by calling the function @code{make-process} with all
arguments undefined).

The function always returns the process object which the subprocess has
been started on. If for some reason the subprocess can't be created an
error of type @code{process-error} is signalled.

The optional argument @var{program} is a string defining the name of
the program to execute, it will be searched for in all the directories
in the @code{PATH} environment variable. The @var{args} are strings to
pass to the subprocess as its arguments.

When defined, the optional arguments overrule the values of the related
components of the process object.

The following example runs the @code{ls} program asynchronously, its output
is sent to the @code{standard-output} stream.

@lisp
(let
    ((process (make-process standard-output)))
  (start-process process "ls" "-s"))
@end lisp
@end defun

Note that when @code{librep} exits it kills all of its asynchronous
subprocesses which are still running without warning.

@defun process-connection-type process
Returns the value of the connection type component of the process object
@var{process}. See the documentation of the @code{set-process-connection-type}
function for the values this may take.
@end defun

@defun set-process-connection-type process symbol
Sets the value of the connection type component of the process object
@var{process} to @var{symbol}, then returns @var{symbol}.

@var{symbol} should be one of the following symbols,

@table @code
@item pty
Use pseudo-terminals to connect to subprocesses running asynchronously on
this process object.

@item pipe
Use standard Unix pipes to connect, this is the default value of this
component.

@item socketpair
Uses a connected pair of sockets.
@end table
@end defun

Note that currently only the @code{pipe} connection type allows the
normal and error output streams of the process to be separated.


@node Synchronous Processes, Process I/O, Asynchronous Processes, Processes
@subsection Synchronous Processes
@cindex Synchronous processes
@cindex Processes, synchronous

When a @dfn{synchronous process} is started @code{librep} waits for it
to terminate before continuing; they are usually used when a Lisp
program must invoke an external program as part of its function, i.e.
the auto-compression feature runs the compression program @code{gzip}
synchronously when it needs to compress a buffer.

Unlike asynchronous processes their is no choice between pipes and
pseudo-terminals for connecting to a subprocess. Instead, it is
possible to link the @code{stdin} channel of a synchronous process to a
named file.

@defun call-process @t{#!optional} process input-file-name program @t{#!rest} args
This function starts a process running on the process object
@var{process}. If @var{process} is undefined a new process object is
created by calling the @code{make} function.

If defined, the string @var{input-file-name} names the file to connect
to the standard input of the subprocess, otherwise the subprocess'
input comes from the null device (@file{/dev/null} on UNIX).

The optional arguments @var{program} and @var{args} define the name of
the program to invoke and any arguments to pass to it. The program will
be searched for in all directories listed in the
@code{process-environment} variable.

If any of the optional parameters are unspecified they should have been
set in the @var{process-object} prior to calling this function.

After successfully creating the new subprocess, this function simply
copies any output from the process to the output stream defined by the
output stream component of the process object. When the subprocess
exits its exit-value is returned (an integer). Note that the exit-value
is the value returned by the @code{process-exit-value} function, see
@ref{Process Information}.

If, for some reason, the new subprocess can't be created an error of
type @code{process-error} is signalled.
@end defun

The following function definition is taken from the @file{gzip.jl}
file, it shows how the @code{call-process} function can be used to
uncompress a file into a buffer (for Jade).

@lisp
;; Uncompress FILE-NAME into the current buffer
(defun gzip-uncompress (file-name)
  (let
      ((proc (make-process (current-buffer))))
    (message (concat "Uncompressing `" file-name "'") t)
    ;; gunzip can do .Z files as well
    (unless (zerop (call-process proc nil "gunzip" "-c" file-name))
      (signal 'file-error (list "Can't gunzip file" file-name)))))
@end lisp

The user is able to interrupt synchronous subprocesses (for example if
they seem to have got wedged somehow). Each time a user-interrupt is
received by @code{librep} (i.e. the @code{INT} signal), a stronger
signal is sent to the subprocess. First an interrupt signal, then a
termination signal, before finally a non-ignoreable quit signal is
sent.


@node Process I/O, Process States, Synchronous Processes, Processes
@subsection Process I/O
@cindex Process I/O

It is only possible for lisp programs to explicitly send input data to
@emph{asynchronous} processes (by the time it's possible to call a
function to send data to a synchronous process, the process will
already have terminated!). Simply use the process object which an
asynchronous process is running on as a normal Lisp input stream, any
strings or characters written to the stream will immediately be copied
to the @code{stdin} channel of the subprocess.

With synchronous processes, the only control over input data possible
is by giving the @code{call-process} function the name of a file
containing the subprocess' input data.

Output data from subprocesses is handled the same way by both
asynchronous and synchronous processes: it is simply copied to the
stream defined by the output stream component of the subprocess'
process object.

@defun process-output-stream process
Returns the value of the output stream component of the process object
@var{process}.
@end defun

@defun set-process-output-stream process stream
Sets the value of the output stream component of the process object
@var{process} to the stream @var{stream}, then returns @var{stream}.
@end defun

By default the @code{stdout} and @code{stderr} streams are combined,
use the @code{set-process-error-stream} function to separate them.
(Note that this currently only works with @code{pipe} connection
types.)

@defun process-error-stream process
Returns the value of the error stream component of the process object
@var{process}.
@end defun

@defun set-process-error-stream process stream
Sets the value of the error stream component of the process object
@var{process} to the stream @var{stream}, then returns @var{stream}.
@end defun

Output from asynchronous subprocesses (this includes changes of state
as well as stream output) is only propagated at well-defined times.
Either when in the read stage of the read-eval-print, or input, loop,
or when the @code{accept-process-output} or @code{sit-for} functions
are called.

@defun accept-process-output @t{#!optional} seconds milliseconds
Wait @var{seconds} plus @var{milliseconds} for output from any
asynchronous subprocesses. If any arrives, process it, then return
false. Otherwise return true. If either of the arguments is
undefined, they count as zero in the addition.
@end defun

@defun sit-for @t{#!optional} seconds milliseconds
Wait for input to arrive and be processed. No more than @var{seconds}
seconds plus @var{milliseconds} milliseconds will be waited. If at the
end of this time no input has arrived, return true. Otherwise
return false if input was found.

Note that this function is only distinct to
@code{accept-process-output} when @code{librep} is embedded in another
application, or an extension has been loaded that provides an event
loop (such as the @code{gtk} binding). In this case other input forms,
such as user input, for example, can preempt the timeout.

This function is exported by the @code{rep.system} module.
@end defun

@xref{Streams}.


@node Process States, Signalling Processes, Process I/O, Processes
@subsection Process States
@cindex Process states

Each process object has a @dfn{state} associated with it; this depends on
the status of the subprocess currently running on the process object (or
not as the case may be).

The possible states are,

@table @dfn
@item running
This state means that the subprocess using this process object is currently
running, i.e. it hasn't been stopped.

@item stopped
Means that the subprocess has been temporarily suspended from running.

@item unused
This means that the process object is free to have a new subprocess created
on it.
@end table

Predicates exist which test whether a given process object is in one of
these states.

@defun process-running-p process-object
Returns true when @var{process-object} is in the running state.
@end defun

@defun process-stopped-p process-object
Returns true when @var{process-object} is in the stopped state.
@end defun

@defun process-in-use-p process-object
Returns true when @var{process-object} is @emph{not} in the unused
state.
@end defun

The following two functions are used to stop and then subsequently
continue a process running.

@defun stop-process process-object @t{#!optional} whole-group
This function suspends execution of the subprocess running on the
process object @var{process-object}.

If @var{whole-group} is true all subprocesses in the
process group of @var{process-object} are stopped.
@end defun

@defun continue-process process-object @t{#!optional} whole-group
Use this function to continue a subprocess executing after it has been
stopped (by the @code{stop-process} function).

If @var{whole-group} is true all subprocesses in the
process group of @var{process-object} are continued.
@end defun

The state change function component of a process object defines a function
which will be called each time the state of the process object changes. If
your program needs to be informed when an asynchronous process terminates
this function is the way to do it.

@defun process-function process
Returns the value of the state change function component of the process object
@var{process}.
@end defun

@defun set-process-function process function
Sets the value of the state change function component of the process object
@var{process} to the function @var{function}, then returns @var{function}.
@end defun

@node Signalling Processes, Process Information, Process States, Processes
@subsection Signalling Processes
@cindex Signalling processes
@cindex Processes, signalling

@defun interrupt-process process-object @t{#!optional} whole-group
Sends the @code{SIGINT} signal to @var{process-object}.
@end defun

@defun kill-process process-object @t{#!optional} whole-group
Sends the @code{SIGKILL} signal to the @var{process-object}.
@end defun

Note that the functions @code{stop-process} and @code{continue-process}
also send signals to the subprocess.

@defun signal-process process signal @t{#!optional} whole-group
Send the signal @var{signal} to the process @var{process}; if
@var{whole-group} is true the signal is also sent to all
processes in the process group of @var{process}.

@var{process} may be either a Lisp process object, or an integer
defining the pid of the process to signal (not necessarily started by
@code{librep}).

@var{signal} may either be an integer defining the actual signal
number, or a symbol naming the signal. All names are as usual but with
the preceding @code{SIG} removed, for example the @code{SIGINT} signal
would be sent by using the symbol @code{INT}. If a named signal doesn't
exist on the current operating system, an error is raised.

Returns true if the signal was sent successfully.
@end defun

As with the UNIX @code{kill} system call, @code{signal-process} may
also be used to test whether a process with a particular pid is
currently active, by using a signal with value zero.


@node Process Information, , Signalling Processes, Processes
@subsection Process Information
@cindex Process information

@defun process-id process-object
This function returns the operating-system identifier associated with the
subprocess currently running on the process object @var{process-object}.
@end defun

@defun process-exit-value process-object
Returns the integer representing the return code of the last subprocess
to be run on @var{process-object}.

If no subprocess has been run on @var{process-object}, @var{process-object}
is currently in the running state or the last subprocess exited abnormally
(i.e. from a terminal signal) false is returned.
@end defun

@defun process-exit-status process-object
This function returns the integer that was the exit status of the last
subprocess which was run on the process object @var{process-object}.

Note that the exit status is @emph{not} the value given to the @code{exit}
function in a C program, use the @code{process-exit-value} to access this
value.

If no process has been run on @var{process-object}, or the process is currently
in the running state false is returned.
@end defun


@node Regular Expressions, Time and Date, Processes, The language
@section Regular Expressions
@cindex Regular expressions
@cindex Regexps

Regular expressions (or @dfn{regexps}) are a powerful method of
matching patterns in strings. @code{librep} uses the @code{regexp(3)}
implementation by Henry Spencer, with some modifications that I have
made. It comes with this banner:

@quotation
Copyright (c) 1986 by University of Toronto.@*
Written by Henry Spencer.  Not derived from licensed software.

Permission is granted to anyone to use this software for any
purpose on any computer system, and to redistribute it freely,
subject to the following restrictions:

@enumerate
@item
The author is not responsible for the consequences of use of
this software, no matter how awful, even if they arise
from defects in it.

@item
The origin of this software must not be misrepresented, either
by explicit claim or by omission.

@item
Altered versions must be plainly marked as such, and must not
be misrepresented as being the original software.
@end enumerate
@end quotation

@menu
* Regexp Syntax::               How to write regular expressions
* Regexp Functions::            How to use them
@end menu


@node Regexp Syntax, Regexp Functions, , Regular Expressions
@subsection Regular Expression Syntax
@cindex Regular expression syntax
@cindex Regexp syntax
@cindex Syntax of regexps

The syntax of a regular expression is as follows (this is adapted from
the manual page):

A regular expression is zero or more @dfn{branches}, separated by
@samp{|}. It matches anything that matches one of the branches.

A branch is zero or more @dfn{pieces}, concatenated. It matches a match
for the first, followed by a match for the second, etc.

A piece is an @dfn{atom} possibly followed by @samp{*}, @samp{+}, or
@samp{?}. An atom followed by @samp{*} matches a sequence of 0 or more
matches of the atom. An atom followed by @samp{+} matches a sequence of
1 or more matches of the atom. An atom followed by @samp{?} matches a
match of the atom, or the null string.

An atom is a regular expression in parentheses (matching a match for
the regular expression), a @dfn{range} (see below), @samp{.} (matching
any single character), @samp{^} (matching the null string at the
beginning of the input string), @samp{$} (matching the null string at
the end of the input string), one of the strings @samp{\s}, @samp{\S},
@samp{\w}, @samp{\W}, @samp{\d}, @samp{\D}, @samp{\b}, @samp{\B}, or a
@samp{\} followed by a single character (matching that character), or a
single character with no other significance (matching that character).

A @dfn{range} is a sequence of characters enclosed in @samp{[]}. It
normally matches any single character from the sequence. If the
sequence begins with @samp{^}, it matches any single character
@emph{not} from the rest of the sequence. If two characters in the
sequence are separated by @samp{-}, this is shorthand for the full list
of ASCII characters between them (e.g. @samp{[0-9]} matches any decimal
digit). To include a literal @samp{]} in the sequence, make it the
first character (following a possible @samp{^}). To include a literal
@samp{-}, make it the first or last character.

Also, any of the @samp{*}, @samp{+} or @samp{?} operators can be
suffixed by a @samp{?} character (i.e. @samp{*?}, @samp{+?},
@samp{??}). The meaning of the operator remains the same but it becomes
@dfn{non-greedy}. This means that it will match the @emph{smallest}
number of characters satisfying the regular expression, instead of the
default behaviour which is to match the @emph{largest}.

The backslash-introduced atoms have the following meanings:

@table @samp
@item \s
Match any whitespace character.

@item \S
Match any non-whitespace character.

@item \w
Match any alphanumeric or underscore character.

@item \W
Match any non-(alphanumeric or underscore) character.

@item \d
Match any numeric character.

@item \D
Match any non-numeric character.

@item \b
Match the null string between two adjacent @samp{\w} and @samp{\W}
characters (in any order).

@item \B
Match the null string that is not between two adjacent @samp{\w} and
@samp{\W} characters.
@end table

@noindent
Some example legal regular expressions could be:

@table @samp
@item ab*a+b
Matches an @samp{a} followed by zero or more @samp{b} characters, followed by
one or more @samp{a} characters, followed by a @samp{b}. For example,
@samp{aaab}, @samp{abbbab}, etc@dots{}

@item (one|two)_three
Matches @samp{one_three} or @samp{two_three}.

@item ^cmd_[0-9]+
@itemx ^cmd_\d+
Matches @samp{cmd_} followed by one or more digits, it must start at the
beginning of the line.
@end table


@node Regexp Functions, , Regexp Syntax, Regular Expressions
@subsection Regexp Functions
@cindex Regexp functions
@cindex Matching strings
@cindex String matching

These functions are exported by the @code{rep.regexp} module.

@defun quote-regexp string
Return a version of @var{string}, such that when used as a regexp, it
will match the original contents of @var{string} verbatim, and nothing
else. This involves quoting regexp meta-characters.

@lisp
(quote-regexp "abc")
    @result{} "abc"

(quote-regexp "a+c")
    @result{} "a\\+c"
@end lisp
@end defun

@defun string-match regexp string @t{#!optional} start ignore-case
Returns true if the string @var{string} matches the regular
expression @var{regexp}. The string matches if executing the regexp at
@emph{any} position in the string succeeds.

When defined, @var{start} is the index of the first character to start
matching at (counting from zero). When @var{ignore-case} is
true the case of matched strings are ignored. Note that
character classes are still case-significant.

@lisp
(string-match "ab+c" "abbbc")
    @result{} t

(string-match "ab+c" "xxxabbbcyyy")
    @result{} t
@end lisp
@end defun

@defun string-looking-at regexp string @t{#!optional} start ignore-case
Similar to @code{string-match}, but only returns true if
@var{string} matches @var{regexp} starting at the character at index
@var{start} in the string (or the first character if @var{start} is
undefined).

@lisp
(string-looking-at "ab+c" "abbbc" 0)
    @result{} t

(string-looking-at "ab+c" "xxxabbbcyyy" 0)
    @result{} ()

(string-looking-at "ab+c" "xxxabbbcyyy" 3)
    @result{} t
@end lisp
@end defun

@defun match-start @t{#!optional} n
Returns the position at which the @var{n}'th parenthesised expression
started in the last successful regexp match. If @var{n} is false
or zero the position of the start of the whole match is returned
instead.

When matching strings, all positions are integers, with the first
character in the string represented by zero. However, extensions that
allow regexps to be matched against other textual inputs may return
different position values.

@lisp
(string-match "x*(foo|bar)y" "xxxbary")
    @result{} t

(match-start 1)
    @result{} 3
@end lisp
@end defun

@defun match-end @t{#!optional} n
Similar to @code{match-start}, but returns the position of the
character following the matched item.

@lisp
(string-match "x*(foo|bar)y" "xxxbary")
    @result{} t

(match-end 1)
    @result{} 6
@end lisp
@end defun

A common use of regular expressions is to match a string, then replace
certain portions of the string with other text.

@defun expand-last-match template
Expand the @var{template} substituting the parenthesised expressions
from the most recent successfully matched regular expression.

@var{template} may contain the following substitution-inducing escape
sequences:

@table @samp
@item \0
@itemx \&
Substitute the whole string matched by the last regexp

@item \@var{n}
Substitute the @var{n}'th parenthensised expression, where 1 <= N <= 9.

@item \\
Substitute a single backslash character.
@end table

@lisp
(string-match "x*(foo|bar)y" "xxxbary")
    @result{} t

(expand-last-match "test-\\1-ing")
    @result{} "test-bar-ing"
@end lisp

Note that double backslashes are required due to the read syntax of
strings (@pxref{Strings}).
@end defun

@defun string-replace regexp template string
Returns the string created by replacing all matches of @var{regexp} in
@var{string} with the result of expanding @var{template} using the
@code{expand-last-match} function.

@lisp
(string-replace "-" "_" "foo-bar-baz")
    @result{} "foo_bar_baz"

(string-replace "&(optional|rest)" "#!\\1" "(a &optional b &rest c)")
    @result{} "(a #!optional b #!rest c)"
@end lisp
@end defun


@node Time and Date, i18n, Regular Expressions, The language
@section Time and Date
@cindex Time and date
@cindex Date and time
@cindex Calendar date and time

This section describes how time and date values are handled in
@code{librep}.

@menu
* Timestamps::                  Internal representation of time
* Formatting Dates::            Creating strings from timestamps
* Parsing Dates::               Reading textual dates
@end menu


@node Timestamps, Formatting Dates, , Time and Date
@subsection Timestamps
@cindex Timestamps
@cindex Date and time, timestamps

As in UNIX, @code{librep} measures time as the number of seconds since
January 1st, 1970 (known as the @dfn{epoch}). For historical reasons
rep stores timestamps as a pair of integers, using a cons cell.

The first integer records the number of whole days since the epoch, the
second records the number of seconds since the start of the day (in
universal time).

These function are exported by the @code{rep.system} module:

@defun current-time
Return the number of seconds since the epoch, in a cons-cell.

@lisp
(current-time)
    @result{} (10744 . 61063)
@end lisp
@end defun

@defun fix-time timestamp
Ensure that the two parts of @var{timestamp} (a pair or integers) are
consistent, simply that the number of seconds is less than the number
of seconds in a whole day. If not, the timestamp is adjusted to meet
this constraint.
@end defun

@defun time-later-p timestamp-1 timestamp-2
Returns true if @var{timestamp-1} is later than @var{timestamp-2}.
@end defun

On the plus side, this scheme won't wrap around as quickly as UNIX's
@code{time_t} will ;-)

The @code{rep.util.time} module also provides some functions for
manipulating timestamps:

@defun time->seconds timestamp
Convert @var{timestamp} to an integer, the number of seconds since the
epoch that it represents.
@end defun

@defun seconds->time seconds
Convert from an integer @var{seconds} to a timestamp object.
@end defun

@defun time- timestamp-1 timestamp-2
Return the number of seconds difference between @var{timestamp-1} and
@var{timestamp-2}.
@end defun

@defvr Constant seconds-per-day
The number of seconds in a 24-hour day.
@end defvr


@node Formatting Dates, Parsing Dates, Timestamps, Time and Date
@subsection Formatting Dates
@cindex Formatting dates
@cindex Dates, formatting as strings
@cindex Time, formatting as strings

Given a timestamp value it is possible to format it as a string, in
many different formats.
 
@defun current-time-string @t{#!optional} timestamp format
Return a string defining @var{timestamp} according to the string
@var{format}. If @var{timestamp} is undefined, the current time is
used.

The @var{format} string may include any of the formatting characters
from the C library's @code{strftime(3)} function. If undefined a
standard, fixed-width, format is used:

@lisp
(current-time-string)
    @result{} "Wed Jun  2 18:07:53 1999"
@end lisp

Some of the possible formatting substitutions include (this is copied
from the GNU libc manual, @pxref{(libc)Formatting Date and Time}):

@table @samp
@item %a
The abbreviated weekday name according to the current locale.

@item %A
The full weekday name according to the current locale.

@item %b
The abbreviated month name according to the current locale.

@item %B
The full month name according to the current locale.

@item %c
The preferred date and time representation for the current locale.

@item %d
The day of the month as a decimal number (range @code{01} to @code{31}).

@item %H
The hour as a decimal number, using a 24-hour clock (range @code{00} to
@code{23}).

@item %I
The hour as a decimal number, using a 12-hour clock (range @code{01} to
@code{12}).

@item %j
The day of the year as a decimal number (range @code{001} to @code{366}).

@item %m
The month as a decimal number (range @code{01} to @code{12}).

@item %M
The minute as a decimal number.

@item %p
Either @samp{am} or @samp{pm}, according to the given time value; or the
corresponding strings for the current locale.

@item %S
The second as a decimal number.

@item %U
The week number of the current year as a decimal number, starting with
the first Sunday as the first day of the first week.

@item %W
The week number of the current year as a decimal number, starting with
the first Monday as the first day of the first week.

@item %w
The day of the week as a decimal number, Sunday being @code{0}.

@item %x
The preferred date representation for the current locale, but without the
time.

@item %X
The preferred time representation for the current locale, but with no date.

@item %y
The year as a decimal number, but without a century (range @code{00} to
@code{99}).

@item %Y
The year as a decimal number, including the century.

@item %Z
The time zone or name or abbreviation (empty if the time zone can't be
determined).

@item %%
A literal @samp{%} character.
@end table

@lisp
(current-time-string nil "%Y-%m-%d")
    @result{} "1999-06-02"
@end lisp
@end defun


@node Parsing Dates, , Formatting Dates, Time and Date
@subsection Parsing Dates
@cindex Parsing dates
@cindex Dates, parsing
@cindex Time, parsing

The @code{date} Lisp library provides rudimentary support for parsing
date and time descriptions to their individual components, and to
timestamps. Evaluate the form @code{(require 'date)} to load this
library.

@defun parse-date string @t{#!optional} start
Returns a vector encoding the date described by @var{string}. If
@var{start} is defined, it specifies the index of the character in the
string to start parsing from.

Each element of the vector contains a separate component of the overall
point in time described by the string. The indices of these elements
are defined by the following constants:

@table @code
@item date-vec-day-abbrev
@vindex date-vec-day-abbrev
The abbreviated name of the day of the week.

@item date-vec-day
@vindex date-vec-day
The numeric day of the month, counting from one.

@item date-vec-month-abbrev
@vindex date-vec-month-abbrev
The abbreviated name of the month.

@item date-vec-month
@vindex date-vec-month
The numeric month of the year, counting from January equals one.

@item date-vec-year
@vindex date-vec-year
The numeric year.

@item date-vec-hour
@vindex date-vec-hour
The numeric hour of the day.

@item date-vec-minute
@vindex date-vec-minute
The numeric minute of the hour.

@item date-vec-second
@vindex date-vec-second
The numeric second of the minute.

@item date-vec-timezone
@vindex date-vec-timezone
If true, a string defining the timezone.

@item date-vec-epoch-time
@vindex date-vec-epoch-time
The timestamp (@pxref{Timestamps}), including the effects of the
timezone, if given.
@end table

@lisp
(current-time-string)
    @result{} "Wed Jun  2 18:37:17 1999"

(parse-date (current-time-string))
    @result{} ["Wed" 2 "Jun" 6 1999 18 37 17 0 (10744 . 67037)]

(parse-date "1999-06-02")
    @result{} ["Tue" 2 "Jun" 6 1999 0 0 0 0 (10744 . 0)]

(parse-date "June 6, 1999")
    @result{} ["" 0 "Jun" 6 1999 0 0 0 0 (10742 . 0)]

(aref (parse-date "June 6, 1999") date-vec-epoch-time)
    @result{} (10742 . 0)
@end lisp
@end defun

XXX provide more information on accepted formats, outputs for
incomplete descriptions, etc@dots{}


@node i18n, System Information, Time and Date, The language
@section Internationalisation
@cindex Internationalisation

@code{librep} has support for internationalisation (or i18n) of text
messages, using the GNU @code{gettext} implementation (@pxref{Top, ,
Overview, gettext, The GNU gettext Manual}), a run-time library
managing the mapping between text strings in the programmer's native
language and in the language of the end user.

Three functions are provided to access the message catalogues
maintained by GNU @code{gettext}. Import the @code{rep.i18n.gettext}
module to load them.

@defun _ string
Attempt to find a native language equivalent of @var{string}. If no
equivalent is found the original string is returned.

Note that this function is always defined, even if the @code{gettext}
module hasn't been required. In this case it always returns the
original string.
@end defun

@defun bindtextdomain domain directory
Tell @code{gettext} that message catalogues for message domain
@var{domain} (a string) can be found under the directory called
@var{directory}.
@end defun

@defun textdomain domain
Note that any strings that are to be translated in the future (until
the next call to @code{textdomain}) are in the domain called
@var{domain} (a string).
@end defun

The usual method of constructing message catalogue templates
(@file{.pot} files) is to run @code{xgettext} on the C source files of
the program (that have been annotated for i18n). librep provides the
@code{rep-xgettext} program to perform the same task for files of Lisp
code.


@node System Information, User Information, i18n, The language
@section System Information
@cindex System information

These definitions are all exported by the @code{rep.system} module.

@defvar operating-system
A symbol naming the current operating system. The only current option
is @code{unix}.
@end defvar

@defun system-name
This function returns a string naming the host that the interpreter is
running on. When possible this be a fully-qualified name (i.e.
including the domain)
@end defun

@defvar rep-build-id
A string describing the environment under which @code{librep} was
built. This will always have the format @samp{@var{date} by
@var{user}@@@var{host}, for @var{arch}.}.

@lisp
rep-build-id
    @result{} "Mon May 17 1999 by john@@tizer.dcs.warwick.ac.uk, for sparc-sun-solaris2.6."
@end lisp
@end defvar

@defvar rep-version
A string describing the current release of @code{librep}.

@lisp
rep-version
    @result{} "1.0"
@end lisp
@end defvar


@node User Information, Environment Variables, System Information, The language
@section User Information
@cindex User information

These functions are exported by the @code{rep.system} module.

@defun user-login-name
This function returns a string containing the login name of the user.

@lisp
(user-login-name)
    @result{} "john"
@end lisp
@end defun

@defun user-full-name @t{#!optional} real-name
This function returns a string containing the `real' name of the user; the
format of the string will depend on the host system.

If @var{real-name} is a string, it defines the name that will be
returned by subsequent calls to this function.

@lisp
(user-full-name)
    @result{} "John Harper"
@end lisp
@end defun

@defun user-home-directory @t{#!optional} user
This function returns the home directory of the user whose login name is
@var{user}, or the current user if @var{user} is undefined. The
returned string will be as returned by @code{file-name-as-directory}
(i.e. terminated by a @samp{/} character under UNIX)

@lisp
(user-home-directory)
    @result{} "/home/john/"
@end lisp
@end defun


@node Environment Variables, String Functions, User Information, The language
@section Environment Variables
@cindex Environment variables

These functions are exported by the @code{rep.system} module.

@defun getenv variable-name
This function returns the value (a string) of the environment variable
called @var{variable-name}. If the specified variable doesn't exist
false is returned.

@lisp
(getenv "OSTYPE")
    @result{} "Linux"
@end lisp
@end defun

@defun setenv variable-name new-value
This function sets the value of the environment variable called
@var{variable-name} to @var{new-value}. @var{new-value} can either be a
string containing the new contents of the variable or false, in
which case the environment variable is deleted.
@end defun

@defun unsetenv variable-name
Deletes any variable in @code{process-environment} named
@var{variable-name}.
@end defun

See also @ref{Process Objects} for the description of the
@code{process-environment} variable.


@node String Functions, Sleeping, Environment Variables, The language
@section String Functions
@cindex String functions

@defun translate-string string map
Applies the @var{map} to each character in the @var{string}. @var{map}
is also string, each character represents the translation for an ASCII
character of that characters position in the string. If the string is
less than 256 chars long any undefined characters will remain
unchanged.

For example, if @var{string} contains the character @samp{A}, with
ASCII code 65, then it would be replaced by the 65th character in the
string @var{map}.

Note that the @var{string} really is modified, no copy is made
@end defun

@defvar upcase-table
A @code{translate-string} compatible translation map to convert
lowercase characters to uppercase characters.
@end defvar

@defvar downcase-table
A map to convert uppercase characters to lowercase.
@end defvar

@defvar flatten-table
A translation map to convert newline characters to spaces.
@end defvar

@lisp
(translate-string "Foo" upcase-table)
    @result{} "FOO"

(translate-string "Foo" downcase-table)
    @result{} "foo"
@end lisp

@defun complete-string template list @t{#!optional} ignore-case
Return a string whose beginning matches the string @var{template}, and
is unique in the set of all strings in @var{list} which also match
@var{template}. If @var{ignore-case} is true, all matching
ignores case of characters.

@lisp
(complete-string "foo" '("bar" "foobar" "forbarf" "foobat"))
    @result{} "fooba"
@end lisp
@end defun

@defun string-head-eq string-1 string-2
Returns t if @var{string-2} matches the beginning of @var{string-1}.

@lisp
(string-head-eq "foobar" "foo")
    @result{} t

(string-head-eq "foo" "foobar")
    @result{} ()
@end lisp
@end defun

@defun string-upper-case-p string
Return true if @var{string} contains no lower case characters.
@end defun

@defun string-lower-case-p string
Return true if @var{string} contains no upper case characters.
@end defun

@defun string-capitalized-p string
Return true if the first character of @var{string} is upper case.
@end defun

@defun string-upcase string
Return a new string, an upper case copy of @var{string}.
@end defun

@defun string-downcase string
Return a new string, a lower case copy of @var{string}.
@end defun

@defun capitalize-string string
Return a new string, a copy of @var{string} with the first character in
upper case.
@end defun

@defun mapconcat function sequence separator
Call @var{function} for each member of @var{sequence}, concatenating
the results. Between each pair of results, insert @var{separator}.
Return the resulting string.
@end defun


@node Sleeping, Beeping, String Functions, The language
@section Sleeping
@cindex Sleeping

@defun sleep-for seconds @t{#!optional} milliseconds
Pause for a @var{seconds} (plus the optional @var{milliseconds}
component) long period of time. Input becoming available will
@emph{not} break the sleep (@pxref{Process I/O}).

This function is exported by the @code{rep.system} module.
@end defun


@node Beeping, Messages, Sleeping, The language
@section Beeping
@cindex Beeping

Use this function to attract the user's attention.

@defun beep
Ring a bell somewhere.
@end defun


@node Messages, Command Line Options, Beeping, The language
@section Messages
@cindex Messages

The @code{message} function will show the user a small message
(typically no more than a single column of text). In graphical
applications it @emph{won't} bring up a separate window, only
displaying the text in a status bar or something similar. In a
console-based environment, the message will be printed to the
@code{stderr} stream, followed by a line break.

@defun message @t{#!optional} display-now
Displays a one-line message, the string @var{message}. If
@var{display-now}, every effort will be made to display the message as
soon as possible, possibly before the next scheduled screen update (if
applicable).

This function is exported by the @code{rep.system} module.
@end defun


@node Command Line Options, Shell Commands, Messages, The language
@section Command Line Options
@cindex Command line options
@cindex Options, command line
@cindex Arguments, command line

As noted earlier any unused command line arguments are made available
to scripts through the @code{command-line-args} variable
(@pxref{Invocation}).

@defvar command-line-args
The list of unused command line arguments, in their original order.
@end defvar

The @code{get-command-line-option} function may be used to scan this
list of arguments. The @code{rep.system} module exports this function.

@defun get-command-line-option option @t{#!optional} requires-arg
Returns t if @var{option} was specified on the command line
(@var{option} is typically a phrase beginning with @samp{--}).

If @var{requires-arg} is true, the option requires a
parameter, the value of which is returned. If a parameter isn't
supplied an error is signalled.
@end defun

@lisp
(setq command-line-args '("--foo" "bar"))
    @result{} ("--foo" "bar")
(get-command-line-option "--foo" t)
    @result{} "bar"
command-line-args
    @result{} ()

(setq command-line-args '("--foo=bar"))
    @result{} ("--foo=bar")
(get-command-line-option "--foo" t)
    @result{} "bar"
command-line-args
    @result{} ()
@end lisp


@node Shell Commands, Timers, Command Line Options, The language
@section Executing Shell Commands
@cindex Executing shell commands
@cindex Shell commands, executing

The subprocess handling of @code{librep} provides a comprehensive
interface to starting and controlling external processes
(@pxref{Processes}). However it can be overkill when all that is
required is to invoke a shell command, with its I/O going to the same
places as the interpreter's.

@defun system command
Execute the shell command @var{command} synchronously, returning its
exit status. An error will be signalled if the shell process could not
be started.

The @code{stdin}, @code{stdout} and @code{stderr} streams of the shell
are left as in the interpreter process.

The subprocesses environment is copied from the current value of the
@code{process-environment} variable.
@end defun

Note that the exit status is @emph{not} the same as the return code of
the command. It depends on the operating system, but under UNIX the
return code can be found through right-shifting the exit status by
eight bits. Low non-zero values represent that the process was killed
by a signal.

It is possible to interrupt a running shell process in the same way as
with a normal synchronous process (@pxref{Synchronous Processes}).
Interrupt the interpreter, it will send progressively harder-to-ignore
signals to the child each interrupt, until it is eventually terminated.


@node Timers, Debugging, Shell Commands, The language
@section Asynchronous Timers
@cindex Asynchronous timers
@cindex Timers, asynchronous

The @code{rep.io.timers} module (@pxref{Modules}) allows a Lisp program
to create multiple asynchronous timers, each of which is primed to call
a specified function after a specified period of time. These functions
only work when the Lisp event loop is being used (i.e. at least one
@code{recursive-edit} is currently in progress).

@defun make-timer function @t{#!optional} seconds milliseconds
Create and return a new timer object. It will be set to call the Lisp
function @var{function} after @var{seconds} seconds plus
@var{milliseconds} milliseconds. @var{function} will be called with a
single argument, the timer object that has just fired.

If both @var{seconds} and @var{milliseconds} are undefined, or zero,
the timer will be created but won't call @var{function}.

After the time interval has passed, and @var{function} has been called,
the timer @emph{will not} be restarted. Use the @code{set-timer}
function to reset it.
@end defun

@defun delete-timer timer
Prevent the timer object @var{timer} from calling the Lisp function
associated with it. Use the @code{set-timer} function to reset it.
@end defun

@defun set-timer timer @t{#!optional} seconds milliseconds
Reset the timer object @var{timer}. If either/both of @var{seconds} and
@var{milliseconds} are defined the interval of the timer will be set to
the specified time period. If neither are defined then the current
interval of the timer is preserved.
@end defun


@node Debugging, Tips, Timers, The language
@section Debugging
@cindex Debugging

When you have written a Lisp program you will have to debug it (unless
all your programs work first time?). There are two main classes of
errors; syntax errors and semantic errors.

Syntax errors occur when the text you've typed out to represent your
program is not a valid representation of a Lisp object (since a program
is simply an ordered set of Lisp objects). When you try to load your
program the Lisp reader will find the syntax error and tell you about,
unfortunately though it probably won't be able to tell you exactly
where the error is.

The most common source of syntax errors is too few or too many
parentheses; the Jade or Emacs @kbd{Ctrl-Meta-f} and @kbd{Ctrl-Meta-b}
commands can be used to show the structure of the program as the Lisp
reader sees it.

Semantic errors are what we normally call bugs---errors in logic, the
program is syntactically correct but doesn't do what you want it to.
For these types of errors librep provides hooks to allow interactive
debugging. The debugger supplied with librep uses these hooks to
implement a simple command line debugger; programs using librep as an
extension language may provide their own debugger interface.

There are several ways to enter the Lisp debugger; functions can be
marked so that they cause the debugger to be entered when they are
called, breakpoints can be written in functions or it can be called
explicitly with a form to step through.

@deffn Command trace symbol
This command marks the symbol @var{symbol} so that each time its value
is dereferenced the debugger is entered when the next form is
evaluated. This can be used to set breakpoints on functions (or
variables).

When called interactively @var{symbol} is prompted for.
@end deffn

@deffn Command untrace symbol
The opposite of @code{trace}---unmarks the symbol.
@end deffn

@defun break
This function causes the debugger to be entered immediately. By putting
the form @code{(break)} at suitable points in your program simple
breakpoints can be created.
@end defun

@deffn Command step form
This function invokes the debugger to step through the form @var{form}.

When called interactively @var{form} is prompted for.
@end deffn

@defun backtrace @t{#!optional} stream
Prints a description of the current Lisp function call stack to
@var{stream} (or @code{standard-output} if @var{stream} is undefined).

@lisp
(backtrace (current-buffer))
     @print{} #<subr backtrace> ((current-buffer)) nil
     @print{} #<closure eval-and-print> ((backtrace (current-buffer))) t
     @result{} t
@end lisp

Each line represents a stack frame, the first item is the called
function, the second is the list of arguments applied to it. The
third item is true if the list of arguments as displayed has
already been evaluated.
@end defun

Whenever the Lisp debugger is entered the form waiting to be evaluated
is printed, preceded by the current depth of execution in angular
brackets. At this point the special debugger commands available are,

@table @samp
@item step
@itemx s
Step into the current form; this means that in a list form the debugger
is used to evaluated each argument in turn.

@item next
@itemx n
Continue evaluating forms normally until the next form at the current
level is entered, then re-enter the debugger.

@item continue
@itemx c
Continue execution normally. Note that this command is the one to use
when an error has been trapped.

@item return @var{form}
@itemx r @var{form}
Evaluate @var{form} then return this value as the result of the current
form.

@item print @var{form}
@itemx p @var{form}
Evaluate @var{form}, then print its value.

@item form
@itemx f
Print the form being debugged.

@item backtrace
@itemx b
Print a backtrace of the current Lisp call stack.
@end table

Entering a null string repeats the previous @samp{next}, @samp{step},
or @samp{continue} command.

After the form has been evaluated (i.e. after you've typed one of the
commands above) the value of the form is printed in the buffer,
prefixed by the string @samp{=> }.

Note that it is also possible to make certain types of errors invoke
the debugger immediately they are signalled, see @ref{Errors}. Also
note that the debugger is unable to step through compiled Lisp code.


@node Tips, , Debugging, The language
@section Tips
@cindex Tips

This section of the manual gives advice about programming in
@code{librep}.

For advice on getting the most out of the compiler, see
@ref{Compilation Tips}.

@menu
* Comment Styles::              Different types of comments
@end menu

@node Comment Styles, , , Tips
@subsection Comment Styles
@cindex Comment styles
@cindex Tips, comment styles
@cindex Style, comments

As already described, single-line comments in Lisp are introduced by a
semi-colon (@samp{;}) character. By convention a different number of
semi-colons is used to introduce different types of comments,

@table @samp
@item ;
A comment referring to the line of Lisp code that it occurs on,
comments of this type are usually indented to the same depth, on the
right of the Lisp code. When editing in Jade's Lisp mode the command
@kbd{Meta-;} can be used to insert a comment of this type.

For example,

@lisp
(defconst op-call #x08)         ;call (stk[n] stk[n-1] ... stk[0])
                                ; pops n values, replacing the
                                ; function with the result.
(defconst op-push #x10)         ;pushes constant # n
@end lisp

@item ;;
Comments starting with two semi-colons are written on a line of their
own and indented to the same depth as the next line of Lisp code. They
describe the following lines of code.

For example,

@lisp
(let
    ((fname (concat file-name ?c)))
  ;; Be sure to remove any partially written dst-file.
  (when (file-exists-p fname)
    (delete-file fname)))
@end lisp

Comments of this type are also placed before a function definition
to describe the function. This saves wasting memory with a documentation
string in a module's internal functions.

For example,

@lisp
;; Compile a form which occurred at the `top-level' into a
;; byte code form.
;; defuns, defmacros, defvars, etc... are treated specially.
;; require forms are evaluated before being output uncompiled;
;; this is so any macros are brought in before they're used.
(defun comp-compile-top-form (form)
  @dots{}
@end lisp

@item ;;;
This type of comment always starts in the first column of the line, they
are used to make general comments about a program and don't refer to any
function or piece of code in particular.

For example,

@lisp
;;; Notes:

;;; Instruction Encoding
;;; ====================
;;; Instructions which get an argument (with opcodes of zero up to
@dots{}
@end lisp

@item ;;;;
Each program should have a comment of this type as its first line, the
body of the comment is the name of the file, two dashes and a brief
description of what the program does. They always start in the first
column.

For example,

@lisp
;;;; compiler.jl -- Simple compiler for Lisp files/forms
@end lisp
@end table

If you adhere to these standards the indentation functions provide by
the Lisp mode will indent your comments to the correct depth.