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
| | @c -*- mode: texinfo; coding: utf-8 -*-
@c This is part of the GNU Emacs Lisp Reference Manual.
@c Copyright (C) 1990-1995, 1998-1999, 2001-2019 Free Software
@c Foundation, Inc.
@c See the file elisp.texi for copying conditions.
@node Control Structures
@chapter Control Structures
@cindex special forms for control structures
@cindex forms for control structures
@cindex control structures
A Lisp program consists of a set of @dfn{expressions}, or
@dfn{forms} (@pxref{Forms}). We control the order of execution of
these forms by enclosing them in @dfn{control structures}. Control
structures are special forms which control when, whether, or how many
times to execute the forms they contain.
@cindex textual order
The simplest order of execution is sequential execution: first form
@var{a}, then form @var{b}, and so on. This is what happens when you
write several forms in succession in the body of a function, or at top
level in a file of Lisp code---the forms are executed in the order
written. We call this @dfn{textual order}. For example, if a function
body consists of two forms @var{a} and @var{b}, evaluation of the
function evaluates first @var{a} and then @var{b}. The result of
evaluating @var{b} becomes the value of the function.
Explicit control structures make possible an order of execution other
than sequential.
Emacs Lisp provides several kinds of control structure, including
other varieties of sequencing, conditionals, iteration, and (controlled)
jumps---all discussed below. The built-in control structures are
special forms since their subforms are not necessarily evaluated or not
evaluated sequentially. You can use macros to define your own control
structure constructs (@pxref{Macros}).
@menu
* Sequencing:: Evaluation in textual order.
* Conditionals:: @code{if}, @code{cond}, @code{when}, @code{unless}.
* Combining Conditions:: @code{and}, @code{or}, @code{not}.
* Pattern-Matching Conditional:: How to use @code{pcase} and friends.
* Iteration:: @code{while} loops.
* Generators:: Generic sequences and coroutines.
* Nonlocal Exits:: Jumping out of a sequence.
@end menu
@node Sequencing
@section Sequencing
@cindex sequencing
@cindex sequential execution
@cindex forms for sequential execution
Evaluating forms in the order they appear is the most common way
control passes from one form to another. In some contexts, such as in a
function body, this happens automatically. Elsewhere you must use a
control structure construct to do this: @code{progn}, the simplest
control construct of Lisp.
A @code{progn} special form looks like this:
@example
@group
(progn @var{a} @var{b} @var{c} @dots{})
@end group
@end example
@noindent
and it says to execute the forms @var{a}, @var{b}, @var{c}, and so on, in
that order. These forms are called the @dfn{body} of the @code{progn} form.
The value of the last form in the body becomes the value of the entire
@code{progn}. @code{(progn)} returns @code{nil}.
@cindex implicit @code{progn}
In the early days of Lisp, @code{progn} was the only way to execute
two or more forms in succession and use the value of the last of them.
But programmers found they often needed to use a @code{progn} in the
body of a function, where (at that time) only one form was allowed. So
the body of a function was made into an implicit @code{progn}:
several forms are allowed just as in the body of an actual @code{progn}.
Many other control structures likewise contain an implicit @code{progn}.
As a result, @code{progn} is not used as much as it was many years ago.
It is needed now most often inside an @code{unwind-protect}, @code{and},
@code{or}, or in the @var{then}-part of an @code{if}.
@defspec progn forms@dots{}
This special form evaluates all of the @var{forms}, in textual
order, returning the result of the final form.
@example
@group
(progn (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The third form"
@end group
@end example
@end defspec
Two other constructs likewise evaluate a series of forms but return
different values:
@defspec prog1 form1 forms@dots{}
This special form evaluates @var{form1} and all of the @var{forms}, in
textual order, returning the result of @var{form1}.
@example
@group
(prog1 (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The first form"
@end group
@end example
Here is a way to remove the first element from a list in the variable
@code{x}, then return the value of that former element:
@example
(prog1 (car x) (setq x (cdr x)))
@end example
@end defspec
@defspec prog2 form1 form2 forms@dots{}
This special form evaluates @var{form1}, @var{form2}, and all of the
following @var{forms}, in textual order, returning the result of
@var{form2}.
@example
@group
(prog2 (print "The first form")
(print "The second form")
(print "The third form"))
@print{} "The first form"
@print{} "The second form"
@print{} "The third form"
@result{} "The second form"
@end group
@end example
@end defspec
@node Conditionals
@section Conditionals
@cindex conditional evaluation
@cindex forms, conditional
Conditional control structures choose among alternatives. Emacs Lisp
has five conditional forms: @code{if}, which is much the same as in
other languages; @code{when} and @code{unless}, which are variants of
@code{if}; @code{cond}, which is a generalized case statement;
and @code{pcase}, which is a generalization of @code{cond}
(@pxref{Pattern-Matching Conditional}).
@defspec if condition then-form else-forms@dots{}
@code{if} chooses between the @var{then-form} and the @var{else-forms}
based on the value of @var{condition}. If the evaluated @var{condition} is
non-@code{nil}, @var{then-form} is evaluated and the result returned.
Otherwise, the @var{else-forms} are evaluated in textual order, and the
value of the last one is returned. (The @var{else} part of @code{if} is
an example of an implicit @code{progn}. @xref{Sequencing}.)
If @var{condition} has the value @code{nil}, and no @var{else-forms} are
given, @code{if} returns @code{nil}.
@code{if} is a special form because the branch that is not selected is
never evaluated---it is ignored. Thus, in this example,
@code{true} is not printed because @code{print} is never called:
@example
@group
(if nil
(print 'true)
'very-false)
@result{} very-false
@end group
@end example
@end defspec
@defmac when condition then-forms@dots{}
This is a variant of @code{if} where there are no @var{else-forms},
and possibly several @var{then-forms}. In particular,
@example
(when @var{condition} @var{a} @var{b} @var{c})
@end example
@noindent
is entirely equivalent to
@example
(if @var{condition} (progn @var{a} @var{b} @var{c}) nil)
@end example
@end defmac
@defmac unless condition forms@dots{}
This is a variant of @code{if} where there is no @var{then-form}:
@example
(unless @var{condition} @var{a} @var{b} @var{c})
@end example
@noindent
is entirely equivalent to
@example
(if @var{condition} nil
@var{a} @var{b} @var{c})
@end example
@end defmac
@defspec cond clause@dots{}
@code{cond} chooses among an arbitrary number of alternatives. Each
@var{clause} in the @code{cond} must be a list. The @sc{car} of this
list is the @var{condition}; the remaining elements, if any, the
@var{body-forms}. Thus, a clause looks like this:
@example
(@var{condition} @var{body-forms}@dots{})
@end example
@code{cond} tries the clauses in textual order, by evaluating the
@var{condition} of each clause. If the value of @var{condition} is
non-@code{nil}, the clause succeeds; then @code{cond} evaluates its
@var{body-forms}, and returns the value of the last of @var{body-forms}.
Any remaining clauses are ignored.
If the value of @var{condition} is @code{nil}, the clause fails, so
the @code{cond} moves on to the following clause, trying its @var{condition}.
A clause may also look like this:
@example
(@var{condition})
@end example
@noindent
Then, if @var{condition} is non-@code{nil} when tested, the @code{cond}
form returns the value of @var{condition}.
If every @var{condition} evaluates to @code{nil}, so that every clause
fails, @code{cond} returns @code{nil}.
The following example has four clauses, which test for the cases where
the value of @code{x} is a number, string, buffer and symbol,
respectively:
@example
@group
(cond ((numberp x) x)
((stringp x) x)
((bufferp x)
(setq temporary-hack x) ; @r{multiple body-forms}
(buffer-name x)) ; @r{in one clause}
((symbolp x) (symbol-value x)))
@end group
@end example
Often we want to execute the last clause whenever none of the previous
clauses was successful. To do this, we use @code{t} as the
@var{condition} of the last clause, like this: @code{(t
@var{body-forms})}. The form @code{t} evaluates to @code{t}, which is
never @code{nil}, so this clause never fails, provided the @code{cond}
gets to it at all. For example:
@example
@group
(setq a 5)
(cond ((eq a 'hack) 'foo)
(t "default"))
@result{} "default"
@end group
@end example
@noindent
This @code{cond} expression returns @code{foo} if the value of @code{a}
is @code{hack}, and returns the string @code{"default"} otherwise.
@end defspec
Any conditional construct can be expressed with @code{cond} or with
@code{if}. Therefore, the choice between them is a matter of style.
For example:
@example
@group
(if @var{a} @var{b} @var{c})
@equiv{}
(cond (@var{a} @var{b}) (t @var{c}))
@end group
@end example
@node Combining Conditions
@section Constructs for Combining Conditions
@cindex combining conditions
This section describes three constructs that are often used together
with @code{if} and @code{cond} to express complicated conditions. The
constructs @code{and} and @code{or} can also be used individually as
kinds of multiple conditional constructs.
@defun not condition
This function tests for the falsehood of @var{condition}. It returns
@code{t} if @var{condition} is @code{nil}, and @code{nil} otherwise.
The function @code{not} is identical to @code{null}, and we recommend
using the name @code{null} if you are testing for an empty list.
@end defun
@defspec and conditions@dots{}
The @code{and} special form tests whether all the @var{conditions} are
true. It works by evaluating the @var{conditions} one by one in the
order written.
If any of the @var{conditions} evaluates to @code{nil}, then the result
of the @code{and} must be @code{nil} regardless of the remaining
@var{conditions}; so @code{and} returns @code{nil} right away, ignoring
the remaining @var{conditions}.
If all the @var{conditions} turn out non-@code{nil}, then the value of
the last of them becomes the value of the @code{and} form. Just
@code{(and)}, with no @var{conditions}, returns @code{t}, appropriate
because all the @var{conditions} turned out non-@code{nil}. (Think
about it; which one did not?)
Here is an example. The first condition returns the integer 1, which is
not @code{nil}. Similarly, the second condition returns the integer 2,
which is not @code{nil}. The third condition is @code{nil}, so the
remaining condition is never evaluated.
@example
@group
(and (print 1) (print 2) nil (print 3))
@print{} 1
@print{} 2
@result{} nil
@end group
@end example
Here is a more realistic example of using @code{and}:
@example
@group
(if (and (consp foo) (eq (car foo) 'x))
(message "foo is a list starting with x"))
@end group
@end example
@noindent
Note that @code{(car foo)} is not executed if @code{(consp foo)} returns
@code{nil}, thus avoiding an error.
@code{and} expressions can also be written using either @code{if} or
@code{cond}. Here's how:
@example
@group
(and @var{arg1} @var{arg2} @var{arg3})
@equiv{}
(if @var{arg1} (if @var{arg2} @var{arg3}))
@equiv{}
(cond (@var{arg1} (cond (@var{arg2} @var{arg3}))))
@end group
@end example
@end defspec
@defspec or conditions@dots{}
The @code{or} special form tests whether at least one of the
@var{conditions} is true. It works by evaluating all the
@var{conditions} one by one in the order written.
If any of the @var{conditions} evaluates to a non-@code{nil} value, then
the result of the @code{or} must be non-@code{nil}; so @code{or} returns
right away, ignoring the remaining @var{conditions}. The value it
returns is the non-@code{nil} value of the condition just evaluated.
If all the @var{conditions} turn out @code{nil}, then the @code{or}
expression returns @code{nil}. Just @code{(or)}, with no
@var{conditions}, returns @code{nil}, appropriate because all the
@var{conditions} turned out @code{nil}. (Think about it; which one
did not?)
For example, this expression tests whether @code{x} is either
@code{nil} or the integer zero:
@example
(or (eq x nil) (eq x 0))
@end example
Like the @code{and} construct, @code{or} can be written in terms of
@code{cond}. For example:
@example
@group
(or @var{arg1} @var{arg2} @var{arg3})
@equiv{}
(cond (@var{arg1})
(@var{arg2})
(@var{arg3}))
@end group
@end example
You could almost write @code{or} in terms of @code{if}, but not quite:
@example
@group
(if @var{arg1} @var{arg1}
(if @var{arg2} @var{arg2}
@var{arg3}))
@end group
@end example
@noindent
This is not completely equivalent because it can evaluate @var{arg1} or
@var{arg2} twice. By contrast, @code{(or @var{arg1} @var{arg2}
@var{arg3})} never evaluates any argument more than once.
@end defspec
@node Pattern-Matching Conditional
@section Pattern-Matching Conditional
@cindex pcase
@cindex pattern matching, programming style
Aside from the four basic conditional forms, Emacs Lisp also
has a pattern-matching conditional form, the @code{pcase} macro,
a hybrid of @code{cond} and @code{cl-case}
(@pxref{Conditionals,,,cl,Common Lisp Extensions})
that overcomes their limitations and introduces
the @dfn{pattern matching programming style}.
The limitations that @code{pcase} overcomes are:
@itemize
@item
The @code{cond} form chooses among alternatives by evaluating the
predicate @var{condition} of each of its clauses
(@pxref{Conditionals}). The primary limitation is that variables
let-bound in @var{condition} are not available to the clause's
@var{body-forms}.
Another annoyance (more an inconvenience than a limitation)
is that when a series of @var{condition} predicates implement
equality tests, there is a lot of repeated code. (@code{cl-case}
solves this inconvenience.)
@item
The @code{cl-case} macro chooses among alternatives by evaluating
the equality of its first argument against a set of specific
values.
Its limitations are two-fold:
@enumerate
@item
The equality tests use @code{eql}.
@item
The values must be known and written in advance.
@end enumerate
@noindent
These render @code{cl-case} unsuitable for strings or compound
data structures (e.g., lists or vectors). (@code{cond} doesn't have
these limitations, but it has others, see above.)
@end itemize
@noindent
Conceptually, the @code{pcase} macro borrows the first-arg focus
of @code{cl-case} and the clause-processing flow of @code{cond},
replacing @var{condition} with a generalization of
the equality test which is a variant of @dfn{pattern matching},
and adding facilities so that you can concisely express a
clause's predicate, and arrange to share let-bindings between
a clause's predicate and @var{body-forms}.
The concise expression of a predicate is known as a @dfn{pattern}.
When the predicate, called on the value of the first arg, returns
non-@code{nil}, we say that ``the pattern matches the value'' (or
sometimes ``the value matches the pattern'').
@menu
* The @code{pcase} macro: pcase Macro. Includes examples and caveats.
* Extending @code{pcase}: Extending pcase. Define new kinds of patterns.
* Backquote-Style Patterns: Backquote Patterns. Structural patterns matching.
* Destructuring with pcase Patterns:: Using pcase patterns to extract subfields.
@end menu
@node pcase Macro
@subsection The @code{pcase} macro
For background, @xref{Pattern-Matching Conditional}.
@defmac pcase expression &rest clauses
Each clause in @var{clauses} has the form:
@w{@code{(@var{pattern} @var{body-forms}@dots{})}}.
Evaluate @var{expression} to determine its value, @var{expval}.
Find the first clause in @var{clauses} whose @var{pattern} matches
@var{expval} and pass control to that clause's @var{body-forms}.
If there is a match, the value of @code{pcase} is the value
of the last of @var{body-forms} in the successful clause.
Otherwise, @code{pcase} evaluates to @code{nil}.
@end defmac
@cindex pcase pattern
Each @var{pattern} has to be a @dfn{pcase pattern}, which can use
either one of the core patterns defined below, or one of the patterns
defined via @code{pcase-defmacro} (@pxref{Extending pcase}).
The rest of this subsection describes different forms of core
patterns, presents some examples, and concludes with important caveats
on using the let-binding facility provided by some pattern forms. A
core pattern can have the following forms:
@table @code
@item _
Matches any @var{expval}.
This is also known as @dfn{don't care} or @dfn{wildcard}.
@item '@var{val}
Matches if @var{expval} equals @var{val}. The comparison is done as
if by @code{equal} (@pxref{Equality Predicates}).
@item @var{keyword}
@itemx @var{integer}
@itemx @var{string}
Matches if @var{expval} equals the literal object.
This is a special case of @code{'@var{val}}, above,
possible because literal objects of these types are self-quoting.
@item @var{symbol}
Matches any @var{expval}, and additionally let-binds @var{symbol} to
@var{expval}, such that this binding is available to
@var{body-forms} (@pxref{Dynamic Binding}).
If @var{symbol} is part of a sequencing pattern @var{seqpat}
(e.g., by using @code{and}, below), the binding is also available to
the portion of @var{seqpat} following the appearance of @var{symbol}.
This usage has some caveats, see @ref{pcase-symbol-caveats,,caveats}.
Two symbols to avoid are @code{t}, which behaves like @code{_}
(above) and is deprecated, and @code{nil}, which signals an error.
Likewise, it makes no sense to bind keyword symbols
(@pxref{Constant Variables}).
@item (pred @var{function})
Matches if the predicate @var{function} returns non-@code{nil}
when called on @var{expval}.
the predicate @var{function} can have one of the following forms:
@table @asis
@item function name (a symbol)
Call the named function with one argument, @var{expval}.
Example: @code{integerp}
@item lambda expression
Call the anonymous function with one argument,
@var{expval} (@pxref{Lambda Expressions}).
Example: @code{(lambda (n) (= 42 n))}
@item function call with @var{n} args
Call the function (the first element of the function call)
with @var{n} arguments (the other elements) and an additional
@var{n}+1-th argument that is @var{expval}.
Example: @code{(= 42)}@*
In this example, the function is @code{=}, @var{n} is one, and
the actual function call becomes: @w{@code{(= 42 @var{expval})}}.
@end table
@item (app @var{function} @var{pattern})
Matches if @var{function} called on @var{expval} returns a
value that matches @var{pattern}.
@var{function} can take one of the forms described for @code{pred},
above. Unlike @code{pred}, however, @code{app} tests the result
against @var{pattern}, rather than against a boolean truth value.
@item (guard @var{boolean-expression})
Matches if @var{boolean-expression} evaluates to non-@code{nil}.
@item (let @var{pattern} @var{expr})
Evaluates @var{expr} to get @var{exprval} and matches if @var{exprval}
matches @var{pattern}. (It is called @code{let} because @var{pattern}
can bind symbols to values using @var{symbol}.)
@end table
@cindex sequencing pattern
A @dfn{sequencing pattern} (also known as @var{seqpat}) is a
pattern that processes its sub-pattern arguments in sequence.
There are two for @code{pcase}: @code{and} and @code{or}.
They behave in a similar manner to the special forms
that share their name (@pxref{Combining Conditions}),
but instead of processing values, they process sub-patterns.
@table @code
@item (and @var{pattern1}@dots{})
Attempts to match @var{pattern1}@dots{}, in order, until one of them
fails to match. In that case, @code{and} likewise fails to match, and
the rest of the sub-patterns are not tested. If all sub-patterns
match, @code{and} matches.
@item (or @var{pattern1} @var{pattern2}@dots{})
Attempts to match @var{pattern1}, @var{pattern2}, @dots{}, in order,
until one of them succeeds. In that case, @code{or} likewise matches,
and the rest of the sub-patterns are not tested. (Note that there
must be at least two sub-patterns.
Simply @w{@code{(or @var{pattern1})}} signals error.)
@c Issue: Is this correct and intended?
@c Are there exceptions, qualifications?
@c (Btw, ``Please avoid it'' is a poor error message.)
To present a consistent environment (@pxref{Intro Eval})
to @var{body-forms} (thus avoiding an evaluation error on match),
if any of the sub-patterns let-binds a set of symbols,
they @emph{must} all bind the same set of symbols.
@end table
@anchor{pcase-example-0}
@subheading Example: Advantage Over @code{cl-case}
Here's an example that highlights some advantages @code{pcase}
has over @code{cl-case}
(@pxref{Conditionals,,,cl,Common Lisp Extensions}).
@example
@group
(pcase (get-return-code x)
;; string
((and (pred stringp) msg)
(message "%s" msg))
@end group
@group
;; symbol
('success (message "Done!"))
('would-block (message "Sorry, can't do it now"))
('read-only (message "The shmliblick is read-only"))
('access-denied (message "You do not have the needed rights"))
@end group
@group
;; default
(code (message "Unknown return code %S" code)))
@end group
@end example
@noindent
With @code{cl-case}, you would need to explicitly declare a local
variable @code{code} to hold the return value of @code{get-return-code}.
Also @code{cl-case} is difficult to use with strings because it
uses @code{eql} for comparison.
@anchor{pcase-example-1}
@subheading Example: Using @code{and}
A common idiom is to write a pattern starting with @code{and},
with one or more @var{symbol} sub-patterns providing bindings
to the sub-patterns that follow (as well as to the body forms).
For example, the following pattern matches single-digit integers.
@example
@group
(and
(pred integerp)
n ; @r{bind @code{n} to @var{expval}}
(guard (<= -9 n 9)))
@end group
@end example
@noindent
First, @code{pred} matches if @w{@code{(integerp @var{expval})}}
evaluates to non-@code{nil}.
Next, @code{n} is a @var{symbol} pattern that matches
anything and binds @code{n} to @var{expval}.
Lastly, @code{guard} matches if the boolean expression
@w{@code{(<= -9 n 9)}} (note the reference to @code{n})
evaluates to non-@code{nil}.
If all these sub-patterns match, @code{and} matches.
@anchor{pcase-example-2}
@subheading Example: Reformulation with @code{pcase}
Here is another example that shows how to reformulate a simple
matching task from its traditional implementation
(function @code{grok/traditional}) to one using
@code{pcase} (function @code{grok/pcase}).
The docstring for both these functions is:
``If OBJ is a string of the form "key:NUMBER", return NUMBER
(a string). Otherwise, return the list ("149" default).''
First, the traditional implementation (@pxref{Regular Expressions}):
@example
@group
(defun grok/traditional (obj)
(if (and (stringp obj)
(string-match "^key:\\([[:digit:]]+\\)$" obj))
(match-string 1 obj)
(list "149" 'default)))
@end group
@group
(grok/traditional "key:0") @result{} "0"
(grok/traditional "key:149") @result{} "149"
(grok/traditional 'monolith) @result{} ("149" default)
@end group
@end example
@noindent
The reformulation demonstrates @var{symbol} binding as well as
@code{or}, @code{and}, @code{pred}, @code{app} and @code{let}.
@example
@group
(defun grok/pcase (obj)
(pcase obj
((or ; @r{line 1}
(and ; @r{line 2}
(pred stringp) ; @r{line 3}
(pred (string-match ; @r{line 4}
"^key:\\([[:digit:]]+\\)$")) ; @r{line 5}
(app (match-string 1) ; @r{line 6}
val)) ; @r{line 7}
(let val (list "149" 'default))) ; @r{line 8}
val))) ; @r{line 9}
@end group
@group
(grok/pcase "key:0") @result{} "0"
(grok/pcase "key:149") @result{} "149"
(grok/pcase 'monolith) @result{} ("149" default)
@end group
@end example
@noindent
The bulk of @code{grok/pcase} is a single clause of a @code{pcase}
form, the pattern on lines 1-8, the (single) body form on line 9.
The pattern is @code{or}, which tries to match in turn its argument
sub-patterns, first @code{and} (lines 2-7), then @code{let} (line 8),
until one of them succeeds.
As in the previous example (@pxref{pcase-example-1,,Example 1}),
@code{and} begins with a @code{pred} sub-pattern to ensure
the following sub-patterns work with an object of the correct
type (string, in this case). If @w{@code{(stringp @var{expval})}}
returns @code{nil}, @code{pred} fails, and thus @code{and} fails, too.
The next @code{pred} (lines 4-5) evaluates
@w{@code{(string-match RX @var{expval})}}
and matches if the result is non-@code{nil}, which means
that @var{expval} has the desired form: @code{key:NUMBER}.
Again, failing this, @code{pred} fails and @code{and}, too.
Lastly (in this series of @code{and} sub-patterns), @code{app}
evaluates @w{@code{(match-string 1 @var{expval})}} (line 6)
to get a temporary value @var{tmp} (i.e., the ``NUMBER'' substring)
and tries to match @var{tmp} against pattern @code{val} (line 7).
Since that is a @var{symbol} pattern, it matches unconditionally
and additionally binds @code{val} to @var{tmp}.
Now that @code{app} has matched, all @code{and} sub-patterns
have matched, and so @code{and} matches.
Likewise, once @code{and} has matched, @code{or} matches
and does not proceed to try sub-pattern @code{let} (line 8).
Let's consider the situation where @code{obj} is not a string,
or it is a string but has the wrong form.
In this case, one of the @code{pred} (lines 3-5) fails to match,
thus @code{and} (line 2) fails to match,
thus @code{or} (line 1) proceeds to try sub-pattern @code{let} (line 8).
First, @code{let} evaluates @w{@code{(list "149" 'default)}}
to get @w{@code{("149" default)}}, the @var{exprval}, and then
tries to match @var{exprval} against pattern @code{val}.
Since that is a @var{symbol} pattern, it matches unconditionally
and additionally binds @code{val} to @var{exprval}.
Now that @code{let} has matched, @code{or} matches.
Note how both @code{and} and @code{let} sub-patterns finish in the
same way: by trying (always successfully) to match against the
@var{symbol} pattern @code{val}, in the process binding @code{val}.
Thus, @code{or} always matches and control always passes
to the body form (line 9).
Because that is the last body form in a successfully matched
@code{pcase} clause, it is the value of @code{pcase} and likewise
the return value of @code{grok/pcase} (@pxref{What Is a Function}).
@anchor{pcase-symbol-caveats}
@subheading Caveats for @var{symbol} in Sequencing Patterns
The preceding examples all use sequencing patterns
which include the @var{symbol}
sub-pattern in some way.
Here are some important details about that usage.
@enumerate
@item When @var{symbol} occurs more than once in @var{seqpat},
the second and subsequent occurrences do not expand to re-binding,
but instead expand to an equality test using @code{eq}.
The following example features a @code{pcase} form
with two clauses and two @var{seqpat}, A and B.
Both A and B first check that @var{expval} is a
pair (using @code{pred}),
and then bind symbols to the @code{car} and @code{cdr}
of @var{expval} (using one @code{app} each).
For A, because symbol @code{st} is mentioned twice, the second
mention becomes an equality test using @code{eq}.
On the other hand, B uses two separate symbols, @code{s1} and
@code{s2}, both of which become independent bindings.
@example
@group
(defun grok (object)
(pcase object
((and (pred consp) ; seqpat A
(app car st) ; first mention: st
(app cdr st)) ; second mention: st
(list 'eq st))
@end group
@group
((and (pred consp) ; seqpat B
(app car s1) ; first mention: s1
(app cdr s2)) ; first mention: s2
(list 'not-eq s1 s2))))
@end group
@group
(let ((s "yow!"))
(grok (cons s s))) @result{} (eq "yow!")
(grok (cons "yo!" "yo!")) @result{} (not-eq "yo!" "yo!")
(grok '(4 2)) @result{} (not-eq 4 (2))
@end group
@end example
@item Side-effecting code referencing @var{symbol} is undefined.
Avoid.
For example, here are two similar functions.
Both use @code{and}, @var{symbol} and @code{guard}:
@example
@group
(defun square-double-digit-p/CLEAN (integer)
(pcase (* integer integer)
((and n (guard (< 9 n 100))) (list 'yes n))
(sorry (list 'no sorry))))
(square-double-digit-p/CLEAN 9) @result{} (yes 81)
(square-double-digit-p/CLEAN 3) @result{} (no 9)
@end group
@group
(defun square-double-digit-p/MAYBE (integer)
(pcase (* integer integer)
((and n (guard (< 9 (incf n) 100))) (list 'yes n))
(sorry (list 'no sorry))))
(square-double-digit-p/MAYBE 9) @result{} (yes 81)
(square-double-digit-p/MAYBE 3) @result{} (yes 9) ; @r{WRONG!}
@end group
@end example
@noindent
The difference is in @var{boolean-expression} in @code{guard}:
@code{CLEAN} references @code{n} simply and directly,
while @code{MAYBE} references @code{n} with a side-effect,
in the expression @code{(incf n)}.
When @code{integer} is 3, here's what happens:
@itemize
@item The first @code{n} binds it to @var{expval},
i.e., the result of evaluating @code{(* 3 3)}, or 9.
@item @var{boolean-expression} is evaluated:
@example
@group
start: (< 9 (incf n) 100)
becomes: (< 9 (setq n (1+ n)) 100)
becomes: (< 9 (setq n (1+ 9)) 100)
@end group
@group
becomes: (< 9 (setq n 10) 100)
; @r{side-effect here!}
becomes: (< 9 n 100) ; @r{@code{n} now bound to 10}
becomes: (< 9 10 100)
becomes: t
@end group
@end example
@item Because the result of the evaluation is non-@code{nil},
@code{guard} matches, @code{and} matches, and
control passes to that clause's body forms.
@end itemize
@noindent
Aside from the mathematical incorrectness of asserting that 9 is a
double-digit integer, there is another problem with @code{MAYBE}.
The body form references @code{n} once more, yet we do not see
the updated value---10---at all. What happened to it?
To sum up, it's best to avoid side-effecting references to
@var{symbol} patterns entirely, not only
in @var{boolean-expression} (in @code{guard}),
but also in @var{expr} (in @code{let})
and @var{function} (in @code{pred} and @code{app}).
@item On match, the clause's body forms can reference the set
of symbols the pattern let-binds.
When @var{seqpat} is @code{and}, this set is
the union of all the symbols each of its sub-patterns let-binds.
This makes sense because, for @code{and} to match,
all the sub-patterns must match.
When @var{seqpat} is @code{or}, things are different:
@code{or} matches at the first sub-pattern that matches;
the rest of the sub-patterns are ignored.
It makes no sense for each sub-pattern to let-bind a different
set of symbols because the body forms have no way to distinguish
which sub-pattern matched and choose among the different sets.
For example, the following is invalid:
@example
@group
(pcase (read-number "Enter an integer: ")
((or (and (pred evenp)
e-num) ; @r{bind @code{e-num} to @var{expval}}
o-num) ; @r{bind @code{o-num} to @var{expval}}
(list e-num o-num)))
@end group
@group
Enter an integer: 42
@error{} Symbol’s value as variable is void: o-num
@end group
@group
Enter an integer: 149
@error{} Symbol’s value as variable is void: e-num
@end group
@end example
@noindent
Evaluating body form @w{@code{(list e-num o-num)}} signals error.
To distinguish between sub-patterns, you can use another symbol,
identical in name in all sub-patterns but differing in value.
Reworking the above example:
@example
@group
(pcase (read-number "Enter an integer: ")
((and num ; @r{line 1}
(or (and (pred evenp) ; @r{line 2}
(let spin 'even)) ; @r{line 3}
(let spin 'odd))) ; @r{line 4}
(list spin num))) ; @r{line 5}
@end group
@group
Enter an integer: 42
@result{} (even 42)
@end group
@group
Enter an integer: 149
@result{} (odd 149)
@end group
@end example
@noindent
Line 1 ``factors out'' the @var{expval} binding with
@code{and} and @var{symbol} (in this case, @code{num}).
On line 2, @code{or} begins in the same way as before,
but instead of binding different symbols, uses @code{let} twice
(lines 3-4) to bind the same symbol @code{spin} in both sub-patterns.
The value of @code{spin} distinguishes the sub-patterns.
The body form references both symbols (line 5).
@end enumerate
@node Extending pcase
@subsection Extending @code{pcase}
@cindex pcase, defining new kinds of patterns
The @code{pcase} macro supports several kinds of patterns
(@pxref{Pattern-Matching Conditional}).
You can add support for other kinds of patterns
using the @code{pcase-defmacro} macro.
@defmac pcase-defmacro name args [doc] &rest body
Define a new kind of pattern for @code{pcase}, to be invoked
as @w{@code{(@var{name} @var{actual-args})}}.
The @code{pcase} macro expands this into a function call
that evaluates @var{body}, whose job it is to
rewrite the invoked pattern into some other pattern,
in an environment where @var{args} are bound to @var{actual-args}.
Additionally, arrange to display @var{doc} along with
the docstring of @code{pcase}.
By convention, @var{doc} should use @code{EXPVAL}
to stand for the result of
evaluating @var{expression} (first arg to @code{pcase}).
@end defmac
@noindent
Typically, @var{body} rewrites the invoked pattern
to use more basic patterns.
Although all patterns eventually reduce to core patterns,
@code{body} need not use core patterns straight away.
The following example defines two patterns, named
@code{less-than} and @code{integer-less-than}.
@example
@group
(pcase-defmacro less-than (n)
"Matches if EXPVAL is a number less than N."
`(pred (> ,n)))
@end group
@group
(pcase-defmacro integer-less-than (n)
"Matches if EXPVAL is an integer less than N."
`(and (pred integerp)
(less-than ,n)))
@end group
@end example
@noindent
Note that the docstrings mention @var{args}
(in this case, only one: @code{n}) in the usual way,
and also mention @code{EXPVAL} by convention.
The first rewrite (i.e., @var{body} for @code{less-than})
uses one core pattern: @code{pred}.
The second uses two core patterns: @code{and} and @code{pred},
as well as the newly-defined pattern @code{less-than}.
Both use a single backquote construct (@pxref{Backquote}).
@node Backquote Patterns
@subsection Backquote-Style Patterns
@cindex backquote-style patterns
@cindex matching, structural
@cindex structural matching
This subsection describes @dfn{backquote-style patterns},
a set of builtin patterns that eases structural matching.
For background, @pxref{Pattern-Matching Conditional}.
Backquote-style patterns are a powerful set of @code{pcase} pattern
extensions (created using @code{pcase-defmacro}) that make it easy to
match @var{expval} against specifications of its @emph{structure}.
For example, to match @var{expval} that must be a list of two
elements whose first element is a specific string and the second
element is any value, you can write a core pattern:
@example
@group
(and (pred listp)
ls
@end group
@group
(guard (= 2 (length ls)))
(guard (string= "first" (car ls)))
(let second-elem (cadr ls)))
@end group
@end example
@noindent
or you can write the equivalent backquote-style pattern:
@example
`("first" ,second-elem)
@end example
@noindent
The backquote-style pattern is more concise,
resembles the structure of @var{expval},
and avoids binding @code{ls}.
A backquote-style pattern has the form @code{`@var{qpat}} where
@var{qpat} can have the following forms:
@table @code
@item (@var{qpat1} . @var{qpat2})
Matches if @var{expval} is a cons cell whose @code{car}
matches @var{qpat1} and whose @code{cdr} matches @var{qpat2}.
This readily generalizes to lists as in
@w{@code{(@var{qpat1} @var{qpat2} @dots{})}}.
@item [@var{qpat1} @var{qpat2} @dots{} @var{qpatm}]
Matches if @var{expval} is a vector of length @var{m} whose
@code{0}..@code{(@var{m}-1)}th elements match @var{qpat1},
@var{qpat2} @dots{} @var{qpatm}, respectively.
@item @var{symbol}
@itemx @var{keyword}
@itemx @var{number}
@itemx @var{string}
Matches if the corresponding element of @var{expval} is
@code{equal} to the specified literal object.
@item ,@var{pattern}
Matches if the corresponding element of @var{expval}
matches @var{pattern}.
Note that @var{pattern} is any kind that @code{pcase} supports.
(In the example above, @code{second-elem} is a @var{symbol}
core pattern; it therefore matches anything,
and let-binds @code{second-elem}.)
@end table
The @dfn{corresponding element} is the portion of @var{expval}
that is in the same structural position as the structural position
of @var{qpat} in the backquote-style pattern.
(In the example above, the corresponding element of
@code{second-elem} is the second element of @var{expval}.)
Here is an example of using @code{pcase} to implement a simple
interpreter for a little expression language
(note that this requires lexical binding for the
lambda expression in the @code{fn} clause to properly
capture @code{body} and @code{arg} (@pxref{Lexical Binding}):
@example
@group
(defun evaluate (form env)
(pcase form
(`(add ,x ,y) (+ (evaluate x env)
(evaluate y env)))
@end group
@group
(`(call ,fun ,arg) (funcall (evaluate fun env)
(evaluate arg env)))
(`(fn ,arg ,body) (lambda (val)
(evaluate body (cons (cons arg val)
env))))
@end group
@group
((pred numberp) form)
((pred symbolp) (cdr (assq form env)))
(_ (error "Syntax error: %S" form))))
@end group
@end example
@noindent
The first three clauses use backquote-style patterns.
@code{`(add ,x ,y)} is a pattern that checks that @code{form}
is a three-element list starting with the literal symbol @code{add},
then extracts the second and third elements and binds them
to symbols @code{x} and @code{y}, respectively.
The clause body evaluates @code{x} and @code{y} and adds the results.
Similarly, the @code{call} clause implements a function call,
and the @code{fn} clause implements an anonymous function definition.
The remaining clauses use core patterns.
@code{(pred numberp)} matches if @code{form} is a number.
On match, the body evaluates it.
@code{(pred symbolp)} matches if @code{form} is a symbol.
On match, the body looks up the symbol in @code{env} and
returns its association.
Finally, @code{_} is the catch-all pattern that
matches anything, so it's suitable for reporting syntax errors.
Here are some sample programs in this small language, including their
evaluation results:
@example
(evaluate '(add 1 2) nil) @result{} 3
(evaluate '(add x y) '((x . 1) (y . 2))) @result{} 3
(evaluate '(call (fn x (add 1 x)) 2) nil) @result{} 3
(evaluate '(sub 1 2) nil) @result{} error
@end example
@node Destructuring with pcase Patterns
@subsection Destructuring with @code{pcase} Patterns
@cindex destructuring with pcase patterns
Pcase patterns not only express a condition on the form of the objects
they can match, but they can also extract sub-fields of those objects.
For example we can extract 2 elements from a list that is the value of
the variable @code{my-list} with the following code:
@example
(pcase my-list
(`(add ,x ,y) (message "Contains %S and %S" x y)))
@end example
This will not only extract @code{x} and @code{y} but will additionally
test that @code{my-list} is a list containing exactly 3 elements and
whose first element is the symbol @code{add}. If any of those tests
fail, @code{pcase} will immediately return @code{nil} without calling
@code{message}.
Extraction of multiple values stored in an object is known as
@dfn{destructuring}. Using @code{pcase} patterns allows to perform
@dfn{destructuring binding}, which is similar to a local binding
(@pxref{Local Variables}), but gives values to multiple elements of
a variable by extracting those values from an object of compatible
structure.
The macros described in this section use @code{pcase} patterns to
perform destructuring binding. The condition of the object to be of
compatible structure means that the object must match the pattern,
because only then the object's subfields can be extracted. For
example:
@example
(pcase-let ((`(add ,x ,y) my-list))
(message "Contains %S and %S" x y))
@end example
@noindent
does the same as the previous example, except that it directly tries
to extract @code{x} and @code{y} from @code{my-list} without first
verifying if @code{my-list} is a list which has the right number of
elements and has @code{add} as its first element. The precise
behavior when the object does not actually match the pattern is
undefined, although the body will not be silently skipped: either an
error is signaled or the body is run with some of the variables
potentially bound to arbitrary values like @code{nil}.
The pcase patterns that are useful for destructuring bindings are
generally those described in @ref{Backquote Patterns}, since they
express a specification of the structure of objects that will match.
For an alternative facility for destructuring binding, see
@ref{seq-let}.
@defmac pcase-let bindings body@dots{}
Perform destructuring binding of variables according to
@var{bindings}, and then evaluate @var{body}.
@var{bindings} is a list of bindings of the form @w{@code{(@var{pattern}
@var{exp})}}, where @var{exp} is an expression to evaluate and
@var{pattern} is a @code{pcase} pattern.
All @var{exp}s are evaluated first, after which they are matched
against their respective @var{pattern}, introducing new variable
bindings that can then be used inside @var{body}. The variable
bindings are produced by destructuring binding of elements of
@var{pattern} to the values of the corresponding elements of the
evaluated @var{exp}.
@end defmac
@defmac pcase-let* bindings body@dots{}
Perform destructuring binding of variables according to
@var{bindings}, and then evaluate @var{body}.
@var{bindings} is a list of bindings of the form @code{(@var{pattern}
@var{exp})}, where @var{exp} is an expression to evaluate and
@var{pattern} is a @code{pcase} pattern. The variable bindings are
produced by destructuring binding of elements of @var{pattern} to the
values of the corresponding elements of the evaluated @var{exp}.
Unlike @code{pcase-let}, but similarly to @code{let*}, each @var{exp}
is matched against its corresponding @var{pattern} before processing
the next element of @var{bindings}, so the variable bindings
introduced in each one of the @var{bindings} are available in the
@var{exp}s of the @var{bindings} that follow it, additionally to
being available in @var{body}.
@end defmac
@defmac pcase-dolist (pattern list) body@dots{}
Execute @var{body} once for each element of @var{list}, on each
iteration performing a destructuring binding of variables in
@var{pattern} to the values of the corresponding subfields of the
element of @var{list}. The bindings are performed as if by
@code{pcase-let}. When @var{pattern} is a simple variable, this ends
up being equivalent to @code{dolist} (@pxref{Iteration}).
@end defmac
@node Iteration
@section Iteration
@cindex iteration
@cindex recursion
@cindex forms, iteration
Iteration means executing part of a program repetitively. For
example, you might want to repeat some computation once for each element
of a list, or once for each integer from 0 to @var{n}. You can do this
in Emacs Lisp with the special form @code{while}:
@defspec while condition forms@dots{}
@code{while} first evaluates @var{condition}. If the result is
non-@code{nil}, it evaluates @var{forms} in textual order. Then it
reevaluates @var{condition}, and if the result is non-@code{nil}, it
evaluates @var{forms} again. This process repeats until @var{condition}
evaluates to @code{nil}.
There is no limit on the number of iterations that may occur. The loop
will continue until either @var{condition} evaluates to @code{nil} or
until an error or @code{throw} jumps out of it (@pxref{Nonlocal Exits}).
The value of a @code{while} form is always @code{nil}.
@example
@group
(setq num 0)
@result{} 0
@end group
@group
(while (< num 4)
(princ (format "Iteration %d." num))
(setq num (1+ num)))
@print{} Iteration 0.
@print{} Iteration 1.
@print{} Iteration 2.
@print{} Iteration 3.
@result{} nil
@end group
@end example
To write a repeat-until loop, which will execute something on each
iteration and then do the end-test, put the body followed by the
end-test in a @code{progn} as the first argument of @code{while}, as
shown here:
@example
@group
(while (progn
(forward-line 1)
(not (looking-at "^$"))))
@end group
@end example
@noindent
This moves forward one line and continues moving by lines until it
reaches an empty line. It is peculiar in that the @code{while} has no
body, just the end test (which also does the real work of moving point).
@end defspec
The @code{dolist} and @code{dotimes} macros provide convenient ways to
write two common kinds of loops.
@defmac dolist (var list [result]) body@dots{}
This construct executes @var{body} once for each element of
@var{list}, binding the variable @var{var} locally to hold the current
element. Then it returns the value of evaluating @var{result}, or
@code{nil} if @var{result} is omitted. For example, here is how you
could use @code{dolist} to define the @code{reverse} function:
@example
(defun reverse (list)
(let (value)
(dolist (elt list value)
(setq value (cons elt value)))))
@end example
@end defmac
@defmac dotimes (var count [result]) body@dots{}
This construct executes @var{body} once for each integer from 0
(inclusive) to @var{count} (exclusive), binding the variable @var{var}
to the integer for the current iteration. Then it returns the value
of evaluating @var{result}, or @code{nil} if @var{result} is omitted.
Use of @var{result} is deprecated. Here is an example of using
@code{dotimes} to do something 100 times:
@example
(dotimes (i 100)
(insert "I will not obey absurd orders\n"))
@end example
@end defmac
@node Generators
@section Generators
@cindex generators
A @dfn{generator} is a function that produces a potentially-infinite
stream of values. Each time the function produces a value, it
suspends itself and waits for a caller to request the next value.
@defmac iter-defun name args [doc] [declare] [interactive] body@dots{}
@code{iter-defun} defines a generator function. A generator function
has the same signature as a normal function, but works differently.
Instead of executing @var{body} when called, a generator function
returns an iterator object. That iterator runs @var{body} to generate
values, emitting a value and pausing where @code{iter-yield} or
@code{iter-yield-from} appears. When @var{body} returns normally,
@code{iter-next} signals @code{iter-end-of-sequence} with @var{body}'s
result as its condition data.
Any kind of Lisp code is valid inside @var{body}, but
@code{iter-yield} and @code{iter-yield-from} cannot appear inside
@code{unwind-protect} forms.
@end defmac
@defmac iter-lambda args [doc] [interactive] body@dots{}
@code{iter-lambda} produces an unnamed generator function that works
just like a generator function produced with @code{iter-defun}.
@end defmac
@defmac iter-yield value
When it appears inside a generator function, @code{iter-yield}
indicates that the current iterator should pause and return
@var{value} from @code{iter-next}. @code{iter-yield} evaluates to the
@code{value} parameter of next call to @code{iter-next}.
@end defmac
@defmac iter-yield-from iterator
@code{iter-yield-from} yields all the values that @var{iterator}
produces and evaluates to the value that @var{iterator}'s generator
function returns normally. While it has control, @var{iterator}
receives values sent to the iterator using @code{iter-next}.
@end defmac
To use a generator function, first call it normally, producing a
@dfn{iterator} object. An iterator is a specific instance of a
generator. Then use @code{iter-next} to retrieve values from this
iterator. When there are no more values to pull from an iterator,
@code{iter-next} raises an @code{iter-end-of-sequence} condition with
the iterator's final value.
It's important to note that generator function bodies only execute
inside calls to @code{iter-next}. A call to a function defined with
@code{iter-defun} produces an iterator; you must drive this
iterator with @code{iter-next} for anything interesting to happen.
Each call to a generator function produces a @emph{different}
iterator, each with its own state.
@defun iter-next iterator value
Retrieve the next value from @var{iterator}. If there are no more
values to be generated (because @var{iterator}'s generator function
returned), @code{iter-next} signals the @code{iter-end-of-sequence}
condition; the data value associated with this condition is the value
with which @var{iterator}'s generator function returned.
@var{value} is sent into the iterator and becomes the value to which
@code{iter-yield} evaluates. @var{value} is ignored for the first
@code{iter-next} call to a given iterator, since at the start of
@var{iterator}'s generator function, the generator function is not
evaluating any @code{iter-yield} form.
@end defun
@defun iter-close iterator
If @var{iterator} is suspended inside an @code{unwind-protect}'s
@code{bodyform} and becomes unreachable, Emacs will eventually run
unwind handlers after a garbage collection pass. (Note that
@code{iter-yield} is illegal inside an @code{unwind-protect}'s
@code{unwindforms}.) To ensure that these handlers are run before
then, use @code{iter-close}.
@end defun
Some convenience functions are provided to make working with
iterators easier:
@defmac iter-do (var iterator) body @dots{}
Run @var{body} with @var{var} bound to each value that
@var{iterator} produces.
@end defmac
The Common Lisp loop facility also contains features for working with
iterators. @xref{Loop Facility,,,cl,Common Lisp Extensions}.
The following piece of code demonstrates some important principles of
working with iterators.
@example
(require 'generator)
(iter-defun my-iter (x)
(iter-yield (1+ (iter-yield (1+ x))))
;; Return normally
-1)
(let* ((iter (my-iter 5))
(iter2 (my-iter 0)))
;; Prints 6
(print (iter-next iter))
;; Prints 9
(print (iter-next iter 8))
;; Prints 1; iter and iter2 have distinct states
(print (iter-next iter2 nil))
;; We expect the iter sequence to end now
(condition-case x
(iter-next iter)
(iter-end-of-sequence
;; Prints -1, which my-iter returned normally
(print (cdr x)))))
@end example
@node Nonlocal Exits
@section Nonlocal Exits
@cindex nonlocal exits
A @dfn{nonlocal exit} is a transfer of control from one point in a
program to another remote point. Nonlocal exits can occur in Emacs Lisp
as a result of errors; you can also use them under explicit control.
Nonlocal exits unbind all variable bindings made by the constructs being
exited.
@menu
* Catch and Throw:: Nonlocal exits for the program's own purposes.
* Examples of Catch:: Showing how such nonlocal exits can be written.
* Errors:: How errors are signaled and handled.
* Cleanups:: Arranging to run a cleanup form if an error happens.
@end menu
@node Catch and Throw
@subsection Explicit Nonlocal Exits: @code{catch} and @code{throw}
@cindex forms for nonlocal exits
Most control constructs affect only the flow of control within the
construct itself. The function @code{throw} is the exception to this
rule of normal program execution: it performs a nonlocal exit on
request. (There are other exceptions, but they are for error handling
only.) @code{throw} is used inside a @code{catch}, and jumps back to
that @code{catch}. For example:
@example
@group
(defun foo-outer ()
(catch 'foo
(foo-inner)))
(defun foo-inner ()
@dots{}
(if x
(throw 'foo t))
@dots{})
@end group
@end example
@noindent
The @code{throw} form, if executed, transfers control straight back to
the corresponding @code{catch}, which returns immediately. The code
following the @code{throw} is not executed. The second argument of
@code{throw} is used as the return value of the @code{catch}.
The function @code{throw} finds the matching @code{catch} based on the
first argument: it searches for a @code{catch} whose first argument is
@code{eq} to the one specified in the @code{throw}. If there is more
than one applicable @code{catch}, the innermost one takes precedence.
Thus, in the above example, the @code{throw} specifies @code{foo}, and
the @code{catch} in @code{foo-outer} specifies the same symbol, so that
@code{catch} is the applicable one (assuming there is no other matching
@code{catch} in between).
Executing @code{throw} exits all Lisp constructs up to the matching
@code{catch}, including function calls. When binding constructs such
as @code{let} or function calls are exited in this way, the bindings
are unbound, just as they are when these constructs exit normally
(@pxref{Local Variables}). Likewise, @code{throw} restores the buffer
and position saved by @code{save-excursion} (@pxref{Excursions}), and
the narrowing status saved by @code{save-restriction}. It also runs
any cleanups established with the @code{unwind-protect} special form
when it exits that form (@pxref{Cleanups}).
The @code{throw} need not appear lexically within the @code{catch}
that it jumps to. It can equally well be called from another function
called within the @code{catch}. As long as the @code{throw} takes place
chronologically after entry to the @code{catch}, and chronologically
before exit from it, it has access to that @code{catch}. This is why
@code{throw} can be used in commands such as @code{exit-recursive-edit}
that throw back to the editor command loop (@pxref{Recursive Editing}).
@cindex CL note---only @code{throw} in Emacs
@quotation
@b{Common Lisp note:} Most other versions of Lisp, including Common Lisp,
have several ways of transferring control nonsequentially: @code{return},
@code{return-from}, and @code{go}, for example. Emacs Lisp has only
@code{throw}. The @file{cl-lib} library provides versions of some of
these. @xref{Blocks and Exits,,,cl,Common Lisp Extensions}.
@end quotation
@defspec catch tag body@dots{}
@cindex tag on run time stack
@code{catch} establishes a return point for the @code{throw} function.
The return point is distinguished from other such return points by
@var{tag}, which may be any Lisp object except @code{nil}. The argument
@var{tag} is evaluated normally before the return point is established.
With the return point in effect, @code{catch} evaluates the forms of the
@var{body} in textual order. If the forms execute normally (without
error or nonlocal exit) the value of the last body form is returned from
the @code{catch}.
If a @code{throw} is executed during the execution of @var{body},
specifying the same value @var{tag}, the @code{catch} form exits
immediately; the value it returns is whatever was specified as the
second argument of @code{throw}.
@end defspec
@defun throw tag value
The purpose of @code{throw} is to return from a return point previously
established with @code{catch}. The argument @var{tag} is used to choose
among the various existing return points; it must be @code{eq} to the value
specified in the @code{catch}. If multiple return points match @var{tag},
the innermost one is used.
The argument @var{value} is used as the value to return from that
@code{catch}.
@kindex no-catch
If no return point is in effect with tag @var{tag}, then a @code{no-catch}
error is signaled with data @code{(@var{tag} @var{value})}.
@end defun
@node Examples of Catch
@subsection Examples of @code{catch} and @code{throw}
One way to use @code{catch} and @code{throw} is to exit from a doubly
nested loop. (In most languages, this would be done with a @code{goto}.)
Here we compute @code{(foo @var{i} @var{j})} for @var{i} and @var{j}
varying from 0 to 9:
@example
@group
(defun search-foo ()
(catch 'loop
(let ((i 0))
(while (< i 10)
(let ((j 0))
(while (< j 10)
(if (foo i j)
(throw 'loop (list i j)))
(setq j (1+ j))))
(setq i (1+ i))))))
@end group
@end example
@noindent
If @code{foo} ever returns non-@code{nil}, we stop immediately and return a
list of @var{i} and @var{j}. If @code{foo} always returns @code{nil}, the
@code{catch} returns normally, and the value is @code{nil}, since that
is the result of the @code{while}.
Here are two tricky examples, slightly different, showing two
return points at once. First, two return points with the same tag,
@code{hack}:
@example
@group
(defun catch2 (tag)
(catch tag
(throw 'hack 'yes)))
@result{} catch2
@end group
@group
(catch 'hack
(print (catch2 'hack))
'no)
@print{} yes
@result{} no
@end group
@end example
@noindent
Since both return points have tags that match the @code{throw}, it goes to
the inner one, the one established in @code{catch2}. Therefore,
@code{catch2} returns normally with value @code{yes}, and this value is
printed. Finally the second body form in the outer @code{catch}, which is
@code{'no}, is evaluated and returned from the outer @code{catch}.
Now let's change the argument given to @code{catch2}:
@example
@group
(catch 'hack
(print (catch2 'quux))
'no)
@result{} yes
@end group
@end example
@noindent
We still have two return points, but this time only the outer one has
the tag @code{hack}; the inner one has the tag @code{quux} instead.
Therefore, @code{throw} makes the outer @code{catch} return the value
@code{yes}. The function @code{print} is never called, and the
body-form @code{'no} is never evaluated.
@node Errors
@subsection Errors
@cindex errors
When Emacs Lisp attempts to evaluate a form that, for some reason,
cannot be evaluated, it @dfn{signals} an @dfn{error}.
When an error is signaled, Emacs's default reaction is to print an
error message and terminate execution of the current command. This is
the right thing to do in most cases, such as if you type @kbd{C-f} at
the end of the buffer.
In complicated programs, simple termination may not be what you want.
For example, the program may have made temporary changes in data
structures, or created temporary buffers that should be deleted before
the program is finished. In such cases, you would use
@code{unwind-protect} to establish @dfn{cleanup expressions} to be
evaluated in case of error. (@xref{Cleanups}.) Occasionally, you may
wish the program to continue execution despite an error in a subroutine.
In these cases, you would use @code{condition-case} to establish
@dfn{error handlers} to recover control in case of error.
Resist the temptation to use error handling to transfer control from
one part of the program to another; use @code{catch} and @code{throw}
instead. @xref{Catch and Throw}.
@menu
* Signaling Errors:: How to report an error.
* Processing of Errors:: What Emacs does when you report an error.
* Handling Errors:: How you can trap errors and continue execution.
* Error Symbols:: How errors are classified for trapping them.
@end menu
@node Signaling Errors
@subsubsection How to Signal an Error
@cindex signaling errors
@dfn{Signaling} an error means beginning error processing. Error
processing normally aborts all or part of the running program and
returns to a point that is set up to handle the error
(@pxref{Processing of Errors}). Here we describe how to signal an
error.
Most errors are signaled automatically within Lisp primitives
which you call for other purposes, such as if you try to take the
@sc{car} of an integer or move forward a character at the end of the
buffer. You can also signal errors explicitly with the functions
@code{error} and @code{signal}.
Quitting, which happens when the user types @kbd{C-g}, is not
considered an error, but it is handled almost like an error.
@xref{Quitting}.
Every error specifies an error message, one way or another. The
message should state what is wrong (``File does not exist''), not how
things ought to be (``File must exist''). The convention in Emacs
Lisp is that error messages should start with a capital letter, but
should not end with any sort of punctuation.
@defun error format-string &rest args
This function signals an error with an error message constructed by
applying @code{format-message} (@pxref{Formatting Strings}) to
@var{format-string} and @var{args}.
These examples show typical uses of @code{error}:
@example
@group
(error "That is an error -- try something else")
@error{} That is an error -- try something else
@end group
@group
(error "Invalid name `%s'" "A%%B")
@error{} Invalid name ‘A%%B’
@end group
@end example
@code{error} works by calling @code{signal} with two arguments: the
error symbol @code{error}, and a list containing the string returned by
@code{format-message}.
Typically grave accent and apostrophe in the format translate to
matching curved quotes, e.g., @t{"Missing `%s'"} might result in
@t{"Missing ‘foo’"}. @xref{Text Quoting Style}, for how to influence
or inhibit this translation.
@strong{Warning:} If you want to use your own string as an error message
verbatim, don't just write @code{(error @var{string})}. If @var{string}
@var{string} contains @samp{%}, @samp{`}, or @samp{'} it may be
reformatted, with undesirable results. Instead, use @code{(error "%s"
@var{string})}.
@end defun
@defun signal error-symbol data
@anchor{Definition of signal}
This function signals an error named by @var{error-symbol}. The
argument @var{data} is a list of additional Lisp objects relevant to
the circumstances of the error.
The argument @var{error-symbol} must be an @dfn{error symbol}---a symbol
defined with @code{define-error}. This is how Emacs Lisp classifies different
sorts of errors. @xref{Error Symbols}, for a description of error symbols,
error conditions and condition names.
If the error is not handled, the two arguments are used in printing
the error message. Normally, this error message is provided by the
@code{error-message} property of @var{error-symbol}. If @var{data} is
non-@code{nil}, this is followed by a colon and a comma separated list
of the unevaluated elements of @var{data}. For @code{error}, the
error message is the @sc{car} of @var{data} (that must be a string).
Subcategories of @code{file-error} are handled specially.
The number and significance of the objects in @var{data} depends on
@var{error-symbol}. For example, with a @code{wrong-type-argument} error,
there should be two objects in the list: a predicate that describes the type
that was expected, and the object that failed to fit that type.
Both @var{error-symbol} and @var{data} are available to any error
handlers that handle the error: @code{condition-case} binds a local
variable to a list of the form @code{(@var{error-symbol} .@:
@var{data})} (@pxref{Handling Errors}).
The function @code{signal} never returns.
@c (though in older Emacs versions it sometimes could).
@example
@group
(signal 'wrong-number-of-arguments '(x y))
@error{} Wrong number of arguments: x, y
@end group
@group
(signal 'no-such-error '("My unknown error condition"))
@error{} peculiar error: "My unknown error condition"
@end group
@end example
@end defun
@cindex user errors, signaling
@defun user-error format-string &rest args
This function behaves exactly like @code{error}, except that it uses
the error symbol @code{user-error} rather than @code{error}. As the
name suggests, this is intended to report errors on the part of the
user, rather than errors in the code itself. For example,
if you try to use the command @code{Info-history-back} (@kbd{l}) to
move back beyond the start of your Info browsing history, Emacs
signals a @code{user-error}. Such errors do not cause entry to the
debugger, even when @code{debug-on-error} is non-@code{nil}.
@xref{Error Debugging}.
@end defun
@cindex CL note---no continuable errors
@quotation
@b{Common Lisp note:} Emacs Lisp has nothing like the Common Lisp
concept of continuable errors.
@end quotation
@node Processing of Errors
@subsubsection How Emacs Processes Errors
@cindex processing of errors
When an error is signaled, @code{signal} searches for an active
@dfn{handler} for the error. A handler is a sequence of Lisp
expressions designated to be executed if an error happens in part of the
Lisp program. If the error has an applicable handler, the handler is
executed, and control resumes following the handler. The handler
executes in the environment of the @code{condition-case} that
established it; all functions called within that @code{condition-case}
have already been exited, and the handler cannot return to them.
If there is no applicable handler for the error, it terminates the
current command and returns control to the editor command loop. (The
command loop has an implicit handler for all kinds of errors.) The
command loop's handler uses the error symbol and associated data to
print an error message. You can use the variable
@code{command-error-function} to control how this is done:
@defvar command-error-function
This variable, if non-@code{nil}, specifies a function to use to
handle errors that return control to the Emacs command loop. The
function should take three arguments: @var{data}, a list of the same
form that @code{condition-case} would bind to its variable;
@var{context}, a string describing the situation in which the error
occurred, or (more often) @code{nil}; and @var{caller}, the Lisp
function which called the primitive that signaled the error.
@end defvar
@cindex @code{debug-on-error} use
An error that has no explicit handler may call the Lisp debugger. The
debugger is enabled if the variable @code{debug-on-error} (@pxref{Error
Debugging}) is non-@code{nil}. Unlike error handlers, the debugger runs
in the environment of the error, so that you can examine values of
variables precisely as they were at the time of the error.
@node Handling Errors
@subsubsection Writing Code to Handle Errors
@cindex error handler
@cindex handling errors
@cindex forms for handling errors
The usual effect of signaling an error is to terminate the command
that is running and return immediately to the Emacs editor command loop.
You can arrange to trap errors occurring in a part of your program by
establishing an error handler, with the special form
@code{condition-case}. A simple example looks like this:
@example
@group
(condition-case nil
(delete-file filename)
(error nil))
@end group
@end example
@noindent
This deletes the file named @var{filename}, catching any error and
returning @code{nil} if an error occurs. (You can use the macro
@code{ignore-errors} for a simple case like this; see below.)
The @code{condition-case} construct is often used to trap errors that
are predictable, such as failure to open a file in a call to
@code{insert-file-contents}. It is also used to trap errors that are
totally unpredictable, such as when the program evaluates an expression
read from the user.
The second argument of @code{condition-case} is called the
@dfn{protected form}. (In the example above, the protected form is a
call to @code{delete-file}.) The error handlers go into effect when
this form begins execution and are deactivated when this form returns.
They remain in effect for all the intervening time. In particular, they
are in effect during the execution of functions called by this form, in
their subroutines, and so on. This is a good thing, since, strictly
speaking, errors can be signaled only by Lisp primitives (including
@code{signal} and @code{error}) called by the protected form, not by the
protected form itself.
The arguments after the protected form are handlers. Each handler
lists one or more @dfn{condition names} (which are symbols) to specify
which errors it will handle. The error symbol specified when an error
is signaled also defines a list of condition names. A handler applies
to an error if they have any condition names in common. In the example
above, there is one handler, and it specifies one condition name,
@code{error}, which covers all errors.
The search for an applicable handler checks all the established handlers
starting with the most recently established one. Thus, if two nested
@code{condition-case} forms offer to handle the same error, the inner of
the two gets to handle it.
If an error is handled by some @code{condition-case} form, this
ordinarily prevents the debugger from being run, even if
@code{debug-on-error} says this error should invoke the debugger.
If you want to be able to debug errors that are caught by a
@code{condition-case}, set the variable @code{debug-on-signal} to a
non-@code{nil} value. You can also specify that a particular handler
should let the debugger run first, by writing @code{debug} among the
conditions, like this:
@example
@group
(condition-case nil
(delete-file filename)
((debug error) nil))
@end group
@end example
@noindent
The effect of @code{debug} here is only to prevent
@code{condition-case} from suppressing the call to the debugger. Any
given error will invoke the debugger only if @code{debug-on-error} and
the other usual filtering mechanisms say it should. @xref{Error Debugging}.
@defmac condition-case-unless-debug var protected-form handlers@dots{}
The macro @code{condition-case-unless-debug} provides another way to
handle debugging of such forms. It behaves exactly like
@code{condition-case}, unless the variable @code{debug-on-error} is
non-@code{nil}, in which case it does not handle any errors at all.
@end defmac
Once Emacs decides that a certain handler handles the error, it
returns control to that handler. To do so, Emacs unbinds all variable
bindings made by binding constructs that are being exited, and
executes the cleanups of all @code{unwind-protect} forms that are
being exited. Once control arrives at the handler, the body of the
handler executes normally.
After execution of the handler body, execution returns from the
@code{condition-case} form. Because the protected form is exited
completely before execution of the handler, the handler cannot resume
execution at the point of the error, nor can it examine variable
bindings that were made within the protected form. All it can do is
clean up and proceed.
Error signaling and handling have some resemblance to @code{throw} and
@code{catch} (@pxref{Catch and Throw}), but they are entirely separate
facilities. An error cannot be caught by a @code{catch}, and a
@code{throw} cannot be handled by an error handler (though using
@code{throw} when there is no suitable @code{catch} signals an error
that can be handled).
@defspec condition-case var protected-form handlers@dots{}
This special form establishes the error handlers @var{handlers} around
the execution of @var{protected-form}. If @var{protected-form} executes
without error, the value it returns becomes the value of the
@code{condition-case} form; in this case, the @code{condition-case} has
no effect. The @code{condition-case} form makes a difference when an
error occurs during @var{protected-form}.
Each of the @var{handlers} is a list of the form @code{(@var{conditions}
@var{body}@dots{})}. Here @var{conditions} is an error condition name
to be handled, or a list of condition names (which can include @code{debug}
to allow the debugger to run before the handler). A condition name of
@code{t} matches any condition. @var{body} is one or more Lisp
expressions to be executed when this handler handles an error. Here
are examples of handlers:
@example
@group
(error nil)
(arith-error (message "Division by zero"))
((arith-error file-error)
(message
"Either division by zero or failure to open a file"))
@end group
@end example
Each error that occurs has an @dfn{error symbol} that describes what
kind of error it is, and which describes also a list of condition names
(@pxref{Error Symbols}). Emacs
searches all the active @code{condition-case} forms for a handler that
specifies one or more of these condition names; the innermost matching
@code{condition-case} handles the error. Within this
@code{condition-case}, the first applicable handler handles the error.
After executing the body of the handler, the @code{condition-case}
returns normally, using the value of the last form in the handler body
as the overall value.
@cindex error description
The argument @var{var} is a variable. @code{condition-case} does not
bind this variable when executing the @var{protected-form}, only when it
handles an error. At that time, it binds @var{var} locally to an
@dfn{error description}, which is a list giving the particulars of the
error. The error description has the form @code{(@var{error-symbol}
. @var{data})}. The handler can refer to this list to decide what to
do. For example, if the error is for failure opening a file, the file
name is the second element of @var{data}---the third element of the
error description.
If @var{var} is @code{nil}, that means no variable is bound. Then the
error symbol and associated data are not available to the handler.
@cindex rethrow a signal
Sometimes it is necessary to re-throw a signal caught by
@code{condition-case}, for some outer-level handler to catch. Here's
how to do that:
@example
(signal (car err) (cdr err))
@end example
@noindent
where @code{err} is the error description variable, the first argument
to @code{condition-case} whose error condition you want to re-throw.
@xref{Definition of signal}.
@end defspec
@defun error-message-string error-descriptor
This function returns the error message string for a given error
descriptor. It is useful if you want to handle an error by printing the
usual error message for that error. @xref{Definition of signal}.
@end defun
@cindex @code{arith-error} example
Here is an example of using @code{condition-case} to handle the error
that results from dividing by zero. The handler displays the error
message (but without a beep), then returns a very large number.
@example
@group
(defun safe-divide (dividend divisor)
(condition-case err
;; @r{Protected form.}
(/ dividend divisor)
@end group
@group
;; @r{The handler.}
(arith-error ; @r{Condition.}
;; @r{Display the usual message for this error.}
(message "%s" (error-message-string err))
1000000)))
@result{} safe-divide
@end group
@group
(safe-divide 5 0)
@print{} Arithmetic error: (arith-error)
@result{} 1000000
@end group
@end example
@noindent
The handler specifies condition name @code{arith-error} so that it
will handle only division-by-zero errors. Other kinds of errors will
not be handled (by this @code{condition-case}). Thus:
@example
@group
(safe-divide nil 3)
@error{} Wrong type argument: number-or-marker-p, nil
@end group
@end example
Here is a @code{condition-case} that catches all kinds of errors,
including those from @code{error}:
@example
@group
(setq baz 34)
@result{} 34
@end group
@group
(condition-case err
(if (eq baz 35)
t
;; @r{This is a call to the function @code{error}.}
(error "Rats! The variable %s was %s, not 35" 'baz baz))
;; @r{This is the handler; it is not a form.}
(error (princ (format "The error was: %s" err))
2))
@print{} The error was: (error "Rats! The variable baz was 34, not 35")
@result{} 2
@end group
@end example
@defmac ignore-errors body@dots{}
This construct executes @var{body}, ignoring any errors that occur
during its execution. If the execution is without error,
@code{ignore-errors} returns the value of the last form in @var{body};
otherwise, it returns @code{nil}.
Here's the example at the beginning of this subsection rewritten using
@code{ignore-errors}:
@example
@group
(ignore-errors
(delete-file filename))
@end group
@end example
@end defmac
@defmac with-demoted-errors format body@dots{}
This macro is like a milder version of @code{ignore-errors}. Rather
than suppressing errors altogether, it converts them into messages.
It uses the string @var{format} to format the message.
@var{format} should contain a single @samp{%}-sequence; e.g.,
@code{"Error: %S"}. Use @code{with-demoted-errors} around code
that is not expected to signal errors, but
should be robust if one does occur. Note that this macro uses
@code{condition-case-unless-debug} rather than @code{condition-case}.
@end defmac
@node Error Symbols
@subsubsection Error Symbols and Condition Names
@cindex error symbol
@cindex error name
@cindex condition name
@cindex user-defined error
@kindex error-conditions
@kindex define-error
When you signal an error, you specify an @dfn{error symbol} to specify
the kind of error you have in mind. Each error has one and only one
error symbol to categorize it. This is the finest classification of
errors defined by the Emacs Lisp language.
These narrow classifications are grouped into a hierarchy of wider
classes called @dfn{error conditions}, identified by @dfn{condition
names}. The narrowest such classes belong to the error symbols
themselves: each error symbol is also a condition name. There are also
condition names for more extensive classes, up to the condition name
@code{error} which takes in all kinds of errors (but not @code{quit}).
Thus, each error has one or more condition names: @code{error}, the
error symbol if that is distinct from @code{error}, and perhaps some
intermediate classifications.
@defun define-error name message &optional parent
In order for a symbol to be an error symbol, it must be defined with
@code{define-error} which takes a parent condition (defaults to @code{error}).
This parent defines the conditions that this kind of error belongs to.
The transitive set of parents always includes the error symbol itself, and the
symbol @code{error}. Because quitting is not considered an error, the set of
parents of @code{quit} is just @code{(quit)}.
@end defun
@cindex peculiar error
In addition to its parents, the error symbol has a @var{message} which
is a string to be printed when that error is signaled but not handled. If that
message is not valid, the error message @samp{peculiar error} is used.
@xref{Definition of signal}.
Internally, the set of parents is stored in the @code{error-conditions}
property of the error symbol and the message is stored in the
@code{error-message} property of the error symbol.
Here is how we define a new error symbol, @code{new-error}:
@example
@group
(define-error 'new-error "A new error" 'my-own-errors)
@end group
@end example
@noindent
This error has several condition names: @code{new-error}, the narrowest
classification; @code{my-own-errors}, which we imagine is a wider
classification; and all the conditions of @code{my-own-errors} which should
include @code{error}, which is the widest of all.
The error string should start with a capital letter but it should
not end with a period. This is for consistency with the rest of Emacs.
Naturally, Emacs will never signal @code{new-error} on its own; only
an explicit call to @code{signal} (@pxref{Definition of signal}) in
your code can do this:
@example
@group
(signal 'new-error '(x y))
@error{} A new error: x, y
@end group
@end example
This error can be handled through any of its condition names.
This example handles @code{new-error} and any other errors in the class
@code{my-own-errors}:
@example
@group
(condition-case foo
(bar nil t)
(my-own-errors nil))
@end group
@end example
The significant way that errors are classified is by their condition
names---the names used to match errors with handlers. An error symbol
serves only as a convenient way to specify the intended error message
and list of condition names. It would be cumbersome to give
@code{signal} a list of condition names rather than one error symbol.
By contrast, using only error symbols without condition names would
seriously decrease the power of @code{condition-case}. Condition names
make it possible to categorize errors at various levels of generality
when you write an error handler. Using error symbols alone would
eliminate all but the narrowest level of classification.
@xref{Standard Errors}, for a list of the main error symbols
and their conditions.
@node Cleanups
@subsection Cleaning Up from Nonlocal Exits
@cindex nonlocal exits, cleaning up
@cindex forms for cleanup
The @code{unwind-protect} construct is essential whenever you
temporarily put a data structure in an inconsistent state; it permits
you to make the data consistent again in the event of an error or
throw. (Another more specific cleanup construct that is used only for
changes in buffer contents is the atomic change group; @ref{Atomic
Changes}.)
@defspec unwind-protect body-form cleanup-forms@dots{}
@cindex cleanup forms
@cindex protected forms
@cindex error cleanup
@cindex unwinding
@code{unwind-protect} executes @var{body-form} with a guarantee that
the @var{cleanup-forms} will be evaluated if control leaves
@var{body-form}, no matter how that happens. @var{body-form} may
complete normally, or execute a @code{throw} out of the
@code{unwind-protect}, or cause an error; in all cases, the
@var{cleanup-forms} will be evaluated.
If @var{body-form} finishes normally, @code{unwind-protect} returns the
value of @var{body-form}, after it evaluates the @var{cleanup-forms}.
If @var{body-form} does not finish, @code{unwind-protect} does not
return any value in the normal sense.
Only @var{body-form} is protected by the @code{unwind-protect}. If any
of the @var{cleanup-forms} themselves exits nonlocally (via a
@code{throw} or an error), @code{unwind-protect} is @emph{not}
guaranteed to evaluate the rest of them. If the failure of one of the
@var{cleanup-forms} has the potential to cause trouble, then protect
it with another @code{unwind-protect} around that form.
The number of currently active @code{unwind-protect} forms counts,
together with the number of local variable bindings, against the limit
@code{max-specpdl-size} (@pxref{Definition of max-specpdl-size,, Local
Variables}).
@end defspec
For example, here we make an invisible buffer for temporary use, and
make sure to kill it before finishing:
@example
@group
(let ((buffer (get-buffer-create " *temp*")))
(with-current-buffer buffer
(unwind-protect
@var{body-form}
(kill-buffer buffer))))
@end group
@end example
@noindent
You might think that we could just as well write @code{(kill-buffer
(current-buffer))} and dispense with the variable @code{buffer}.
However, the way shown above is safer, if @var{body-form} happens to
get an error after switching to a different buffer! (Alternatively,
you could write a @code{save-current-buffer} around @var{body-form},
to ensure that the temporary buffer becomes current again in time to
kill it.)
Emacs includes a standard macro called @code{with-temp-buffer} which
expands into more or less the code shown above (@pxref{Definition of
with-temp-buffer,, Current Buffer}). Several of the macros defined in
this manual use @code{unwind-protect} in this way.
@findex ftp-login
Here is an actual example derived from an FTP package. It creates a
process (@pxref{Processes}) to try to establish a connection to a remote
machine. As the function @code{ftp-login} is highly susceptible to
numerous problems that the writer of the function cannot anticipate, it
is protected with a form that guarantees deletion of the process in the
event of failure. Otherwise, Emacs might fill up with useless
subprocesses.
@example
@group
(let ((win nil))
(unwind-protect
(progn
(setq process (ftp-setup-buffer host file))
(if (setq win (ftp-login process host user password))
(message "Logged in")
(error "Ftp login failed")))
(or win (and process (delete-process process)))))
@end group
@end example
This example has a small bug: if the user types @kbd{C-g} to
quit, and the quit happens immediately after the function
@code{ftp-setup-buffer} returns but before the variable @code{process} is
set, the process will not be killed. There is no easy way to fix this bug,
but at least it is very unlikely.
|