all messages for Emacs-related lists mirrored at yhetil.org
 help / color / mirror / code / Atom feed
blob e7cca509b19d705902a1be7187b996b4f82727c9 136484 bytes (raw)
name: contrib/lisp/org-export.el 	 # note: path name is non-authoritative(*)

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
 
;;; org-export.el --- Generic Export Engine For Org

;; Copyright (C) 2012  Free Software Foundation, Inc.

;; Author: Nicolas Goaziou <n.goaziou at gmail dot com>
;; Keywords: outlines, hypermedia, calendar, wp

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

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

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

;;; Commentary:

;; This library implements a generic export engine for Org, built on
;; its syntactical parser: Org Elements.

;; Besides that parser, the generic exporter is made of three distinct
;; parts:

;; - The communication channel consists in a property list, which is
;;   created and updated during the process.  Its use is to offer
;;   every piece of information, would it be about initial environment
;;   or contextual data, all in a single place.  The exhaustive list
;;   of properties is given in "The Communication Channel" section of
;;   this file.

;; - The transcoder walks the parse tree, ignores or treat as plain
;;   text elements and objects according to export options, and
;;   eventually calls back-end specific functions to do the real
;;   transcoding, concatenating their return value along the way.

;; - The filter system is activated at the very beginning and the very
;;   end of the export process, and each time an element or an object
;;   has been converted.  It is the entry point to fine-tune standard
;;   output from back-end transcoders.

;; The core function is `org-export-as'.  It returns the transcoded
;; buffer as a string.

;; In order to derive an exporter out of this generic implementation,
;; one can define a transcode function for each element or object.
;; Such function should return a string for the corresponding element,
;; without any trailing space, or nil.  It must accept three
;; arguments:
;; 1. the element or object itself,
;; 2. its contents, or nil when it isn't recursive,
;; 3. the property list used as a communication channel.

;; If no such function is found, that element or object type will
;; simply be ignored, along with any separating blank line.  The same
;; will happen if the function returns the nil value.  If that
;; function returns the empty string, the type will be ignored, but
;; the blank lines will be kept.

;; Contents, when not nil, are stripped from any global indentation
;; (although the relative one is preserved).  They also always end
;; with a single newline character.

;; These functions must follow a strict naming convention:
;; `org-BACKEND-TYPE' where, obviously, BACKEND is the name of the
;; export back-end and TYPE the type of the element or object handled.

;; Moreover, two additional functions can be defined.  On the one
;; hand, `org-BACKEND-template' returns the final transcoded string,
;; and can be used to add a preamble and a postamble to document's
;; body.  It must accept two arguments: the transcoded string and the
;; property list containing export options.  On the other hand,
;; `org-BACKEND-plain-text', when defined, is to be called on every
;; text not recognized as an element or an object.  It must accept two
;; arguments: the text string and the information channel.

;; Any back-end can define its own variables.  Among them, those
;; customizables should belong to the `org-export-BACKEND' group.
;; Also, a special variable, `org-BACKEND-option-alist', allows to
;; define buffer keywords and "#+options:" items specific to that
;; back-end.  See `org-export-option-alist' for supported defaults and
;; syntax.

;; Tools for common tasks across back-ends are implemented in the
;; penultimate part of this file.  A dispatcher for standard back-ends
;; is provided in the last one.

;;; Code:
(eval-when-compile (require 'cl))
(require 'org-element)
;; Require major back-ends and publishing tools
(require 'org-e-ascii "../../EXPERIMENTAL/org-e-ascii.el")
(require 'org-e-html "../../EXPERIMENTAL/org-e-html.el")
(require 'org-e-latex "../../EXPERIMENTAL/org-e-latex.el")
(require 'org-e-odt "../../EXPERIMENTAL/org-e-odt.el")
(require 'org-e-publish "../../EXPERIMENTAL/org-e-publish.el")


\f
;;; Internal Variables

;; Among internal variables, the most important is
;; `org-export-option-alist'.  This variable define the global export
;; options, shared between every exporter, and how they are acquired.

(defconst org-export-max-depth 19
  "Maximum nesting depth for headlines, counting from 0.")

(defconst org-export-option-alist
  '((:author "AUTHOR" nil user-full-name t)
    (:creator "CREATOR" nil org-export-creator-string)
    (:date "DATE" nil nil t)
    (:description "DESCRIPTION" nil nil newline)
    (:email "EMAIL" nil user-mail-address t)
    (:exclude-tags "EXPORT_EXCLUDE_TAGS" nil org-export-exclude-tags split)
    (:headline-levels nil "H" org-export-headline-levels)
    (:keywords "KEYWORDS" nil nil space)
    (:language "LANGUAGE" nil org-export-default-language t)
    (:preserve-breaks nil "\\n" org-export-preserve-breaks)
    (:section-numbers nil "num" org-export-with-section-numbers)
    (:select-tags "EXPORT_SELECT_TAGS" nil org-export-select-tags split)
    (:time-stamp-file nil "timestamp" org-export-time-stamp-file)
    (:title "TITLE" nil nil space)
    (:with-archived-trees nil "arch" org-export-with-archived-trees)
    (:with-author nil "author" org-export-with-author)
    (:with-creator nil "creator" org-export-with-creator)
    (:with-drawers nil "d" org-export-with-drawers)
    (:with-email nil "email" org-export-with-email)
    (:with-emphasize nil "*" org-export-with-emphasize)
    (:with-entities nil "e" org-export-with-entities)
    (:with-fixed-width nil ":" org-export-with-fixed-width)
    (:with-footnotes nil "f" org-export-with-footnotes)
    (:with-priority nil "pri" org-export-with-priority)
    (:with-special-strings nil "-" org-export-with-special-strings)
    (:with-sub-superscript nil "^" org-export-with-sub-superscripts)
    (:with-toc nil "toc" org-export-with-toc)
    (:with-tables nil "|" org-export-with-tables)
    (:with-tags nil "tags" org-export-with-tags)
    (:with-tasks nil "tasks" org-export-with-tasks)
    (:with-timestamps nil "<" org-export-with-timestamps)
    (:with-todo-keywords nil "todo" org-export-with-todo-keywords))
  "Alist between export properties and ways to set them.

The car of the alist is the property name, and the cdr is a list
like \(KEYWORD OPTION DEFAULT BEHAVIOUR\) where:

KEYWORD is a string representing a buffer keyword, or nil.
OPTION is a string that could be found in an #+OPTIONS: line.
DEFAULT is the default value for the property.
BEHAVIOUR determine how Org should handle multiple keywords for
the same property.  It is a symbol among:
  nil       Keep old value and discard the new one.
  t         Replace old value with the new one.
  `space'   Concatenate the values, separating them with a space.
  `newline' Concatenate the values, separating them with
	    a newline.
  `split'   Split values at white spaces, and cons them to the
	    previous list.

KEYWORD and OPTION have precedence over DEFAULT.

All these properties should be back-end agnostic.  For back-end
specific properties, define a similar variable named
`org-BACKEND-option-alist', replacing BACKEND with the name of
the appropriate back-end.  You can also redefine properties
there, as they have precedence over these.")

(defconst org-export-special-keywords
  '("SETUP_FILE" "OPTIONS" "MACRO")
  "List of in-buffer keywords that require special treatment.
These keywords are not directly associated to a property.  The
way they are handled must be hard-coded into
`org-export-get-inbuffer-options' function.")

(defconst org-export-filters-alist
  '((:filter-babel-call . org-export-filter-babel-call-functions)
    (:filter-center-block . org-export-filter-center-block-functions)
    (:filter-comment . org-export-filter-comment-functions)
    (:filter-comment-block . org-export-filter-comment-block-functions)
    (:filter-drawer . org-export-filter-drawer-functions)
    (:filter-dynamic-block . org-export-filter-dynamic-block-functions)
    (:filter-emphasis . org-export-filter-emphasis-functions)
    (:filter-entity . org-export-filter-entity-functions)
    (:filter-example-block . org-export-filter-example-block-functions)
    (:filter-export-block . org-export-filter-export-block-functions)
    (:filter-export-snippet . org-export-filter-export-snippet-functions)
    (:filter-final-output . org-export-filter-final-output-functions)
    (:filter-fixed-width . org-export-filter-fixed-width-functions)
    (:filter-footnote-definition . org-export-filter-footnote-definition-functions)
    (:filter-footnote-reference . org-export-filter-footnote-reference-functions)
    (:filter-headline . org-export-filter-headline-functions)
    (:filter-horizontal-rule . org-export-filter-horizontal-rule-functions)
    (:filter-inline-babel-call . org-export-filter-inline-babel-call-functions)
    (:filter-inline-src-block . org-export-filter-inline-src-block-functions)
    (:filter-inlinetask . org-export-filter-inlinetask-functions)
    (:filter-item . org-export-filter-item-functions)
    (:filter-keyword . org-export-filter-keyword-functions)
    (:filter-latex-environment . org-export-filter-latex-environment-functions)
    (:filter-latex-fragment . org-export-filter-latex-fragment-functions)
    (:filter-line-break . org-export-filter-line-break-functions)
    (:filter-link . org-export-filter-link-functions)
    (:filter-macro . org-export-filter-macro-functions)
    (:filter-paragraph . org-export-filter-paragraph-functions)
    (:filter-parse-tree . org-export-filter-parse-tree-functions)
    (:filter-plain-list . org-export-filter-plain-list-functions)
    (:filter-plain-text . org-export-filter-plain-text-functions)
    (:filter-property-drawer . org-export-filter-property-drawer-functions)
    (:filter-quote-block . org-export-filter-quote-block-functions)
    (:filter-quote-section . org-export-filter-quote-section-functions)
    (:filter-radio-target . org-export-filter-radio-target-functions)
    (:filter-section . org-export-filter-section-functions)
    (:filter-special-block . org-export-filter-special-block-functions)
    (:filter-src-block . org-export-filter-src-block-functions)
    (:filter-statistics-cookie . org-export-filter-statistics-cookie-functions)
    (:filter-subscript . org-export-filter-subscript-functions)
    (:filter-superscript . org-export-filter-superscript-functions)
    (:filter-table . org-export-filter-table-functions)
    (:filter-target . org-export-filter-target-functions)
    (:filter-time-stamp . org-export-filter-time-stamp-functions)
    (:filter-verbatim . org-export-filter-verbatim-functions)
    (:filter-verse-block . org-export-filter-verse-block-functions))
  "Alist between filters properties and initial values.

The key of each association is a property name accessible through
the communication channel its value is a configurable global
variable defining initial filters.

This list is meant to install user specified filters.  Back-end
developers may install their own filters using
`org-BACKEND-filters-alist', where BACKEND is the name of the
considered back-end.  Filters defined there will always be
prepended to the current list, so they always get applied
first.")

(defconst org-export-default-inline-image-rule
  `(("file" .
     ,(format "\\.%s\\'"
	      (regexp-opt
	       '("png" "jpeg" "jpg" "gif" "tiff" "tif" "xbm"
		 "xpm" "pbm" "pgm" "ppm") t))))
  "Default rule for link matching an inline image.
This rule applies to links with no description.  By default, it
will be considered as an inline image if it targets a local file
whose extension is either \"png\", \"jpeg\", \"jpg\", \"gif\",
\"tiff\", \"tif\", \"xbm\", \"xpm\", \"pbm\", \"pgm\" or \"ppm\".
See `org-export-inline-image-p' for more information about
rules.")


\f
;;; User-configurable Variables

;; Configuration for the masses.

;; They should never be evaled directly, as their value is to be
;; stored in a property list (cf. `org-export-option-alist').

(defgroup org-export nil
  "Options for exporting Org mode files."
  :tag "Org Export"
  :group 'org)

(defgroup org-export-general nil
  "General options for export engine."
  :tag "Org Export General"
  :group 'org-export)

(defcustom org-export-with-archived-trees 'headline
  "Whether sub-trees with the ARCHIVE tag should be exported.

This can have three different values:
nil         Do not export, pretend this tree is not present.
t           Do export the entire tree.
`headline'  Only export the headline, but skip the tree below it.

This option can also be set with the #+OPTIONS line,
e.g. \"arch:nil\"."
  :group 'org-export-general
  :type '(choice
	  (const :tag "Not at all" nil)
	  (const :tag "Headline only" 'headline)
	  (const :tag "Entirely" t)))

(defcustom org-export-with-author t
  "Non-nil means insert author name into the exported file.
This option can also be set with the #+OPTIONS line,
e.g. \"author:nil\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-creator 'comment
  "Non-nil means the postamble should contain a creator sentence.

The sentence can be set in `org-export-creator-string' and
defaults to \"Generated by Org mode XX in Emacs XXX.\".

If the value is `comment' insert it as a comment."
  :group 'org-export-general
  :type '(choice
	  (const :tag "No creator sentence" nil)
	  (const :tag "Sentence as a comment" 'comment)
	  (const :tag "Insert the sentence" t)))

(defcustom org-export-creator-string
  (format "Generated by Org mode %s in Emacs %s." org-version emacs-version)
  "String to insert at the end of the generated document."
  :group 'org-export-general
  :type '(string :tag "Creator string"))

(defcustom org-export-with-drawers t
  "Non-nil means export contents of standard drawers.

When t, all drawers are exported.  This may also be a list of
drawer names to export.  This variable doesn't apply to
properties drawers.

This option can also be set with the #+OPTIONS line,
e.g. \"d:nil\"."
  :group 'org-export-general
  :type '(choice
	  (const :tag "All drawers" t)
	  (const :tag "None" nil)
	  (repeat :tag "Selected drawers"
		  (string :tag "Drawer name"))))

(defcustom org-export-with-email nil
  "Non-nil means insert author email into the exported file.
This option can also be set with the #+OPTIONS line,
e.g. \"email:t\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-emphasize t
  "Non-nil means interpret *word*, /word/, and _word_ as emphasized text.

If the export target supports emphasizing text, the word will be
typeset in bold, italic, or underlined, respectively.  Not all
export backends support this.

This option can also be set with the #+OPTIONS line, e.g. \"*:nil\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-exclude-tags '("noexport")
  "Tags that exclude a tree from export.

All trees carrying any of these tags will be excluded from
export.  This is without condition, so even subtrees inside that
carry one of the `org-export-select-tags' will be removed.

This option can also be set with the #+EXPORT_EXCLUDE_TAGS:
keyword."
  :group 'org-export-general
  :type '(repeat (string :tag "Tag")))

(defcustom org-export-with-fixed-width t
  "Non-nil means lines starting with \":\" will be in fixed width font.

This can be used to have pre-formatted text, fragments of code
etc.  For example:
  : ;; Some Lisp examples
  : (while (defc cnt)
  :   (ding))
will be looking just like this in also HTML.  See also the QUOTE
keyword.  Not all export backends support this.

This option can also be set with the #+OPTIONS line, e.g. \"::nil\"."
  :group 'org-export-translation
  :type 'boolean)

(defcustom org-export-with-footnotes t
  "Non-nil means Org footnotes should be exported.
This option can also be set with the #+OPTIONS line,
e.g. \"f:nil\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-headline-levels 3
  "The last level which is still exported as a headline.

Inferior levels will produce itemize lists when exported.  Note
that a numeric prefix argument to an exporter function overrides
this setting.

This option can also be set with the #+OPTIONS line, e.g. \"H:2\"."
  :group 'org-export-general
  :type 'integer)

(defcustom org-export-default-language "en"
  "The default language for export and clocktable translations, as a string.
This may have an association in
`org-clock-clocktable-language-setup'."
  :group 'org-export-general
  :type '(string :tag "Language"))

(defcustom org-export-preserve-breaks nil
  "Non-nil means preserve all line breaks when exporting.

Normally, in HTML output paragraphs will be reformatted.

This option can also be set with the #+OPTIONS line,
e.g. \"\\n:t\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-entities t
  "Non-nil means interpret entities when exporting.

For example, HTML export converts \\alpha to &alpha; and \\AA to
&Aring;.

For a list of supported names, see the constant `org-entities'
and the user option `org-entities-user'.

This option can also be set with the #+OPTIONS line,
e.g. \"e:nil\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-priority nil
  "Non-nil means include priority cookies in export.

When nil, remove priority cookies for export.

This option can also be set with the #+OPTIONS line,
e.g. \"pri:t\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-section-numbers t
  "Non-nil means add section numbers to headlines when exporting.

When set to an integer n, numbering will only happen for
headlines whose relative level is higher or equal to n.

This option can also be set with the #+OPTIONS line,
e.g. \"num:t\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-select-tags '("export")
  "Tags that select a tree for export.

If any such tag is found in a buffer, all trees that do not carry
one of these tags will be ignored during export.  Inside trees
that are selected like this, you can still deselect a subtree by
tagging it with one of the `org-export-exclude-tags'.

This option can also be set with the #+EXPORT_SELECT_TAGS:
keyword."
  :group 'org-export-general
  :type '(repeat (string :tag "Tag")))

(defcustom org-export-with-special-strings t
  "Non-nil means interpret \"\-\", \"--\" and \"---\" for export.

When this option is turned on, these strings will be exported as:

  Org     HTML     LaTeX
 -----+----------+--------
  \\-    &shy;      \\-
  --    &ndash;    --
  ---   &mdash;    ---
  ...   &hellip;   \ldots

This option can also be set with the #+OPTIONS line,
e.g. \"-:nil\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-sub-superscripts t
  "Non-nil means interpret \"_\" and \"^\" for export.

When this option is turned on, you can use TeX-like syntax for
sub- and superscripts.  Several characters after \"_\" or \"^\"
will be considered as a single item - so grouping with {} is
normally not needed.  For example, the following things will be
parsed as single sub- or superscripts.

 10^24   or   10^tau     several digits will be considered 1 item.
 10^-12  or   10^-tau    a leading sign with digits or a word
 x^2-y^3                 will be read as x^2 - y^3, because items are
			 terminated by almost any nonword/nondigit char.
 x_{i^2} or   x^(2-i)    braces or parenthesis do grouping.

Still, ambiguity is possible - so when in doubt use {} to enclose
the sub/superscript.  If you set this variable to the symbol
`{}', the braces are *required* in order to trigger
interpretations as sub/superscript.  This can be helpful in
documents that need \"_\" frequently in plain text.

This option can also be set with the #+OPTIONS line,
e.g. \"^:nil\"."
  :group 'org-export-general
  :type '(choice
	  (const :tag "Interpret them" t)
	  (const :tag "Curly brackets only" {})
	  (const :tag "Do not interpret them" nil)))

(defcustom org-export-with-toc t
  "Non-nil means create a table of contents in exported files.

The TOC contains headlines with levels up
to`org-export-headline-levels'.  When an integer, include levels
up to N in the toc, this may then be different from
`org-export-headline-levels', but it will not be allowed to be
larger than the number of headline levels.  When nil, no table of
contents is made.

This option can also be set with the #+OPTIONS line,
e.g. \"toc:nil\" or \"toc:3\"."
  :group 'org-export-general
  :type '(choice
	  (const :tag "No Table of Contents" nil)
	  (const :tag "Full Table of Contents" t)
	  (integer :tag "TOC to level")))

(defcustom org-export-with-tables t
  "If non-nil, lines starting with \"|\" define a table.
For example:

  | Name        | Address  | Birthday  |
  |-------------+----------+-----------|
  | Arthur Dent | England  | 29.2.2100 |

This option can also be set with the #+OPTIONS line, e.g. \"|:nil\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-tags t
  "If nil, do not export tags, just remove them from headlines.

If this is the symbol `not-in-toc', tags will be removed from
table of contents entries, but still be shown in the headlines of
the document.

This option can also be set with the #+OPTIONS line,
e.g. \"tags:nil\"."
  :group 'org-export-general
  :type '(choice
	  (const :tag "Off" nil)
	  (const :tag "Not in TOC" not-in-toc)
	  (const :tag "On" t)))

(defcustom org-export-with-tasks t
  "Non-nil means include TODO items for export.
This may have the following values:
t                    include tasks independent of state.
todo                 include only tasks that are not yet done.
done                 include only tasks that are already done.
nil                  remove all tasks before export
list of keywords     keep only tasks with these keywords"
  :group 'org-export-general
  :type '(choice
	  (const :tag "All tasks" t)
	  (const :tag "No tasks" nil)
	  (const :tag "Not-done tasks" todo)
	  (const :tag "Only done tasks" done)
	  (repeat :tag "Specific TODO keywords"
		  (string :tag "Keyword"))))

(defcustom org-export-time-stamp-file t
  "Non-nil means insert a time stamp into the exported file.
The time stamp shows when the file was created.

This option can also be set with the #+OPTIONS line,
e.g. \"timestamp:nil\"."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-timestamps t
  "If nil, do not export time stamps and associated keywords."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-with-todo-keywords t
  "Non-nil means include TODO keywords in export.
When nil, remove all these keywords from the export.")

(defcustom org-export-allow-BIND 'confirm
  "Non-nil means allow #+BIND to define local variable values for export.
This is a potential security risk, which is why the user must
confirm the use of these lines."
  :group 'org-export-general
  :type '(choice
	  (const :tag "Never" nil)
	  (const :tag "Always" t)
	  (const :tag "Ask a confirmation for each file" confirm)))

(defcustom org-export-snippet-translation-alist nil
  "Alist between export snippets back-ends and exporter back-ends.

This variable allows to provide shortcuts for export snippets.

For example, with a value of '\(\(\"h\" . \"html\"\)\), the HTML
back-end will recognize the contents of \"@h{<b>}\" as HTML code
while every other back-end will ignore it."
  :group 'org-export-general
  :type '(repeat
	  (cons
	   (string :tag "Shortcut")
	   (string :tag "Back-end"))))

(defcustom org-export-coding-system nil
  "Coding system for the exported file."
  :group 'org-export-general
  :type 'coding-system)

(defcustom org-export-copy-to-kill-ring t
  "Non-nil means exported stuff will also be pushed onto the kill ring."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-initial-scope 'buffer
  "The initial scope when exporting with `org-export-dispatch'.
This variable can be either set to `buffer' or `subtree'."
  :group 'org-export-general
  :type '(choice
	  (const :tag "Export current buffer" 'buffer)
	  (const :tag "Export current subtree" 'subtree)))

(defcustom org-export-show-temporary-export-buffer t
  "Non-nil means show buffer after exporting to temp buffer.
When Org exports to a file, the buffer visiting that file is ever
shown, but remains buried.  However, when exporting to a temporary
buffer, that buffer is popped up in a second window.  When this variable
is nil, the buffer remains buried also in these cases."
  :group 'org-export-general
  :type 'boolean)

(defcustom org-export-dispatch-use-expert-ui nil
  "Non-nil means using a non-intrusive `org-export-dispatch'.
In that case, no help buffer is displayed.  Though, an indicator
for current export scope is added to the prompt \(i.e. \"b\" when
output is restricted to body only, \"s\" when it is restricted to
the current subtree and \"v\" when only visible elements are
considered for export\).  Also, \[?] allows to switch back to
standard mode."
  :group 'org-export-general
  :type 'boolean)


\f
;;; The Communication Channel

;; During export process, every function has access to a number of
;; properties.  They are of three types:

;; 1. Environment options are collected once at the very beginning of
;;    the process, out of the original buffer and configuration.
;;    Associated to the parse tree, they make an Org closure.
;;    Collecting them is handled by `org-export-get-environment'
;;    function.
;;
;;    Most environment options are defined through the
;;    `org-export-option-alist' variable.
;;
;; 2. Tree properties are extracted directly from the parsed tree,
;;    just before export, by `org-export-collect-tree-properties'.
;;
;; 3. Local options are updated during parsing, and their value
;;    depends on the level of recursion.  For now, only `:ignore-list'
;;    belongs to that category.

;; Here is the full list of properties available during transcode
;; process, with their category (option, tree or local) and their
;; value type.

;; + `:author' :: Author's name.
;;   - category :: option
;;   - type :: string

;; + `:back-end' :: Current back-end used for transcoding.
;;   - category :: tree
;;   - type :: symbol

;; + `:creator' :: String to write as creation information.
;;   - category :: option
;;   - type :: string

;; + `:date' :: String to use as date.
;;   - category :: option
;;   - type :: string

;; + `:description' :: Description text for the current data.
;;   - category :: option
;;   - type :: string

;; + `:email' :: Author's email.
;;   - category :: option
;;   - type :: string

;; + `:exclude-tags' :: Tags for exclusion of subtrees from export
;;      process.
;;   - category :: option
;;   - type :: list of strings

;; + `:footnote-definition-alist' :: Alist between footnote labels and
;;     their definition, as parsed data.  Only non-inlined footnotes
;;     are represented in this alist.  Also, every definition isn't
;;     guaranteed to be referenced in the parse tree.  The purpose of
;;     this property is to preserve definitions from oblivion
;;     (i.e. when the parse tree comes from a part of the original
;;     buffer), it isn't meant for direct use in a back-end.  To
;;     retrieve a definition relative to a reference, use
;;     `org-export-get-footnote-definition' instead.
;;   - category :: option
;;   - type :: alist (STRING . LIST)

;; + `:headline-levels' :: Maximum level being exported as an
;;      headline.  Comparison is done with the relative level of
;;      headlines in the parse tree, not necessarily with their
;;      actual level.
;;   - category :: option
;;   - type :: integer

;; + `:headline-offset' :: Difference between relative and real level
;;      of headlines in the parse tree.  For example, a value of -1
;;      means a level 2 headline should be considered as level
;;      1 (cf. `org-export-get-relative-level').
;;   - category :: tree
;;   - type :: integer

;; + `:headline-numbering' :: Alist between headlines and their
;;      numbering, as a list of numbers
;;      (cf. `org-export-get-headline-number').
;;   - category :: tree
;;   - type :: alist (INTEGER . LIST)

;; + `:ignore-list' :: List of elements and objects that should be
;;      ignored during export.
;;   - category :: local
;;   - type :: list of elements and objects

;; + `:input-file' :: Full path to input file, if any.
;;   - category :: option
;;   - type :: string or nil

;; + `:keywords' :: List of keywords attached to data.
;;   - category :: option
;;   - type :: string

;; + `:language' :: Default language used for translations.
;;   - category :: option
;;   - type :: string

;; + `:macro-input-file' :: Macro returning file name of input file,
;;   or nil.
;;   - category :: option
;;   - type :: string or nil

;; + `:parse-tree' :: Whole parse tree, available at any time during
;;                   transcoding.
;;   - category :: global
;;   - type :: list (as returned by `org-element-parse-buffer')

;; + `:preserve-breaks' :: Non-nil means transcoding should preserve
;;      all line breaks.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:section-numbers' :: Non-nil means transcoding should add
;;      section numbers to headlines.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:select-tags' :: List of tags enforcing inclusion of sub-trees
;;                    in transcoding.  When such a tag is present,
;;                    subtrees without it are de facto excluded from
;;                    the process.  See `use-select-tags'.
;;   - category :: option
;;   - type :: list of strings

;; + `:target-list' :: List of targets encountered in the parse tree.
;;                    This is used to partly resolve "fuzzy" links
;;                    (cf. `org-export-resolve-fuzzy-link').
;;   - category :: tree
;;   - type :: list of strings

;; + `:time-stamp-file' :: Non-nil means transcoding should insert
;;      a time stamp in the output.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-archived-trees' :: Non-nil when archived subtrees should
;;      also be transcoded.  If it is set to the `headline' symbol,
;;      only the archived headline's name is retained.
;;   - category :: option
;;   - type :: symbol (nil, t, `headline')

;; + `:with-author' :: Non-nil means author's name should be included
;;                    in the output.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-creator' :: Non-nild means a creation sentence should be
;;      inserted at the end of the transcoded string.  If the value
;;      is `comment', it should be commented.
;;   - category :: option
;;   - type :: symbol (`comment', nil, t)

;; + `:with-drawers' :: Non-nil means drawers should be exported.  If
;;      its value is a list of names, only drawers with such names
;;      will be transcoded.
;;   - category :: option
;;   - type :: symbol (nil, t) or list of strings

;; + `:with-email' :: Non-nil means output should contain author's
;;                   email.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-emphasize' :: Non-nil means emphasized text should be
;;      interpreted.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-fixed-width' :: Non-nil if transcoder should interpret
;;      strings starting with a colon as a fixed-with (verbatim) area.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-footnotes' :: Non-nil if transcoder should interpret
;;      footnotes.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-priority' :: Non-nil means transcoding should include
;;      priority cookies.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-special-strings' :: Non-nil means transcoding should
;;      interpret special strings in plain text.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-sub-superscript' :: Non-nil means transcoding should
;;      interpret subscript and superscript.  With a value of "{}",
;;      only interpret those using curly brackets.
;;   - category :: option
;;   - type :: symbol (nil, {}, t)

;; + `:with-tables' :: Non-nil means transcoding should interpret
;;                    tables.
;;   - category :: option
;;   - type :: symbol (nil, t)

;; + `:with-tags' :: Non-nil means transcoding should keep tags in
;;                  headlines.  A `not-in-toc' value will remove them
;;                  from the table of contents, if any, nonetheless.
;;   - category :: option
;;   - type :: symbol (nil, t, `not-in-toc')

;; + `:with-tasks' :: Non-nil means transcoding should include
;;                   headlines with a TODO keyword.  A `todo' value
;;                   will only include headlines with a todo type
;;                   keyword while a `done' value will do the
;;                   contrary.  If a list of strings is provided, only
;;                   tasks with keywords belonging to that list will
;;                   be kept.
;;   - category :: option
;;   - type :: symbol (t, todo, done, nil) or list of strings

;; + `:with-timestamps' :: Non-nil means transcoding should include
;;      time stamps and associated keywords.  Otherwise, completely
;;      remove them.
;;   - category :: option
;;   - type :: symbol: (t, nil)

;; + `:with-toc' :: Non-nil means that a table of contents has to be
;;                 added to the output.  An integer value limits its
;;                 depth.
;;   - category :: option
;;   - type :: symbol (nil, t or integer)

;; + `:with-todo-keywords' :: Non-nil means transcoding should
;;      include TODO keywords.
;;   - category :: option
;;   - type :: symbol (nil, t)


;;;; Environment Options

;; Environment options encompass all parameters defined outside the
;; scope of the parsed data.  They come from five sources, in
;; increasing precedence order:
;;
;; - Global variables,
;; - Options keyword symbols,
;; - Buffer keywords,
;; - Subtree properties.

;; The central internal function with regards to environment options
;; is `org-export-get-environment'.  It updates global variables with
;; "#+BIND:" keywords, then retrieve and prioritize properties from
;; the different sources.

;;  The internal functions doing the retrieval are:
;;  `org-export-parse-option-keyword' ,
;;  `org-export-get-subtree-options' ,
;;  `org-export-get-inbuffer-options' and
;;  `org-export-get-global-options'.
;;
;;  Some properties, which do not rely on the previous sources but
;;  still depend on the original buffer, are taken care of with
;;  `org-export-initial-options'.

;; Also, `org-export-confirm-letbind' and `org-export-install-letbind'
;; take care of the part relative to "#+BIND:" keywords.

(defun org-export-get-environment (&optional backend subtreep ext-plist)
  "Collect export options from the current buffer.

Optional argument BACKEND is a symbol specifying which back-end
specific options to read, if any.

When optional argument SUBTREEP is non-nil, assume the export is
done against the current sub-tree.

Third optional argument EXT-PLIST is a property list with
external parameters overriding Org default settings, but still
inferior to file-local settings."
  ;; First install #+BIND variables.
  (org-export-install-letbind-maybe)
  ;; Get and prioritize export options...
  (let ((options (org-combine-plists
		  ;; ... from global variables...
		  (org-export-get-global-options backend)
		  ;; ... from buffer's name (default title)...
		  `(:title
		    ,(or (let ((file (buffer-file-name (buffer-base-buffer))))
			   (and file
				(file-name-sans-extension
				 (file-name-nondirectory file))))
			 (buffer-name (buffer-base-buffer))))
		  ;; ... from an external property list...
		  ext-plist
		  ;; ... from in-buffer settings...
		  (org-export-get-inbuffer-options
		   backend
		   (and buffer-file-name
			(org-remove-double-quotes buffer-file-name)))
		  ;; ... and from subtree, when appropriate.
		  (and subtreep (org-export-get-subtree-options)))))
    ;; Add initial options.
    (setq options (append (org-export-initial-options) options))
    ;; Return plist.
    options))

(defun org-export-parse-option-keyword (options &optional backend)
  "Parse an OPTIONS line and return values as a plist.
Optional argument BACKEND is a symbol specifying which back-end
specific items to read, if any."
  (let* ((all
	  (append org-export-option-alist
		  (and backend
		       (let ((var (intern
				   (format "org-%s-option-alist" backend))))
			 (and (boundp var) (eval var))))))
	 ;; Build an alist between #+OPTION: item and property-name.
	 (alist (delq nil
		      (mapcar (lambda (e)
				(when (nth 2 e) (cons (regexp-quote (nth 2 e))
						      (car e))))
			      all)))
	 plist)
    (mapc (lambda (e)
	    (when (string-match (concat "\\(\\`\\|[ \t]\\)"
					(car e)
					":\\(([^)\n]+)\\|[^ \t\n\r;,.]*\\)")
				options)
	      (setq plist (plist-put plist
				     (cdr e)
				     (car (read-from-string
					   (match-string 2 options)))))))
	  alist)
    plist))

(defun org-export-get-subtree-options ()
  "Get export options in subtree at point.

Assume point is at subtree's beginning.

Return options as a plist."
  (let (prop plist)
    (when (setq prop (progn (looking-at org-todo-line-regexp)
			    (or (save-match-data
				  (org-entry-get (point) "EXPORT_TITLE"))
				(org-match-string-no-properties 3))))
      (setq plist
	    (plist-put
	     plist :title
	     (org-element-parse-secondary-string
	      prop
	      (cdr (assq 'keyword org-element-string-restrictions))))))
    (when (setq prop (org-entry-get (point) "EXPORT_TEXT"))
      (setq plist (plist-put plist :text prop)))
    (when (setq prop (org-entry-get (point) "EXPORT_AUTHOR"))
      (setq plist (plist-put plist :author prop)))
    (when (setq prop (org-entry-get (point) "EXPORT_DATE"))
      (setq plist (plist-put plist :date prop)))
    (when (setq prop (org-entry-get (point) "EXPORT_OPTIONS"))
      (setq plist (org-export-add-options-to-plist plist prop)))
    plist))

(defun org-export-get-inbuffer-options (&optional backend files)
  "Return current buffer export options, as a plist.

Optional argument BACKEND, when non-nil, is a symbol specifying
which back-end specific options should also be read in the
process.

Optional argument FILES is a list of setup files names read so
far, used to avoid circular dependencies.

Assume buffer is in Org mode.  Narrowing, if any, is ignored."
  (org-with-wide-buffer
   (goto-char (point-min))
   (let ((case-fold-search t) plist)
     ;; 1. Special keywords, as in `org-export-special-keywords'.
     (let ((special-re (org-make-options-regexp org-export-special-keywords)))
       (while (re-search-forward special-re nil t)
	 (let ((element (org-element-at-point)))
	   (when (eq (org-element-type element) 'keyword)
	     (let* ((key (upcase (org-element-property :key element)))
		    (val (org-element-property :value element))
		    (prop
		     (cond
		      ((string= key "SETUP_FILE")
		       (let ((file
			      (expand-file-name
			       (org-remove-double-quotes (org-trim val)))))
			 ;; Avoid circular dependencies.
			 (unless (member file files)
			   (with-temp-buffer
			     (insert (org-file-contents file 'noerror))
			     (org-mode)
			     (org-export-get-inbuffer-options
			      backend (cons file files))))))
		      ((string= key "OPTIONS")
		       (org-export-parse-option-keyword val backend))
		      ((string= key "MACRO")
		       (when (string-match
			      "^\\([-a-zA-Z0-9_]+\\)\\(?:[ \t]+\\(.*?\\)[ \t]*$\\)?"
			      val)
			 (let ((key
				(intern
				 (concat ":macro-"
					 (downcase (match-string 1 val)))))
			       (value (org-match-string-no-properties 2 val)))
			   (cond
			    ((not value) nil)
			    ;; Value will be evaled.  Leave it as-is.
			    ((string-match "\\`(eval\\>" value)
			     (list key value))
			    ;; Value has to be parsed for nested
			    ;; macros.
			    (t
			     (list
			      key
			      (let ((restr
				     (cdr
				      (assq 'macro
					    org-element-object-restrictions))))
				(org-element-parse-secondary-string
				 ;; If user explicitly asks for
				 ;; a newline, be sure to preserve it
				 ;; from further filling with
				 ;; `hard-newline'.  Also replace
				 ;; "\\n" with "\n", "\\\n" with "\\n"
				 ;; and so on...
				 (replace-regexp-in-string
				  "\\(\\\\\\\\\\)n" "\\\\"
				  (replace-regexp-in-string
				   "\\(?:^\\|[^\\\\]\\)\\(\\\\n\\)"
				   hard-newline value nil nil 1)
				  nil nil 1)
				 restr)))))))))))
	       (setq plist (org-combine-plists plist prop)))))))
     ;; 2. Standard options, as in `org-export-option-alist'.
     (let* ((all (append org-export-option-alist
			 ;; Also look for back-end specific options
			 ;; if BACKEND is defined.
			 (and backend
			      (let ((var
				     (intern
				      (format "org-%s-option-alist" backend))))
				(and (boundp var) (eval var))))))
	    ;; Build alist between keyword name and property name.
	    (alist
	     (delq nil (mapcar
			(lambda (e) (when (nth 1 e) (cons (nth 1 e) (car e))))
			all)))
	    ;; Build regexp matching all keywords associated to export
	    ;; options.  Note: the search is case insensitive.
	    (opt-re (org-make-options-regexp
		     (delq nil (mapcar (lambda (e) (nth 1 e)) all)))))
       (goto-char (point-min))
       (while (re-search-forward opt-re nil t)
	 (let ((element (org-element-at-point)))
	   (when (eq (org-element-type element) 'keyword)
	     (let* ((key (upcase (org-element-property :key element)))
		    (val (org-element-property :value element))
		    (prop (cdr (assoc key alist)))
		    (behaviour (nth 4 (assq prop all))))
	       (setq plist
		     (plist-put
		      plist prop
		      ;; Handle value depending on specified BEHAVIOUR.
		      (case behaviour
			(space
			 (if (not (plist-get plist prop)) (org-trim val)
			   (concat (plist-get plist prop) " " (org-trim val))))
			(newline
			 (org-trim
			  (concat (plist-get plist prop) "\n" (org-trim val))))
			(split
			 `(,@(plist-get plist prop) ,@(org-split-string val)))
			('t val)
			(otherwise (if (not (plist-member plist prop)) val
				     (plist-get plist prop))))))))))
       ;; Parse keywords specified in `org-element-parsed-keywords'.
       (mapc
	(lambda (key)
	  (let* ((prop (cdr (assoc key alist)))
		 (value (and prop (plist-get plist prop))))
	    (when (stringp value)
	      (setq plist
		    (plist-put
		     plist prop
		     (org-element-parse-secondary-string
		      value
		      (cdr (assq 'keyword org-element-string-restrictions))))))))
	org-element-parsed-keywords))
     ;; 3. Return final value.
     plist)))

(defun org-export-get-global-options (&optional backend)
  "Return global export options as a plist.

Optional argument BACKEND, if non-nil, is a symbol specifying
which back-end specific export options should also be read in the
process."
  (let ((all (append org-export-option-alist
		     (and backend
			  (let ((var (intern
				      (format "org-%s-option-alist" backend))))
			    (and (boundp var) (eval var))))))
	;; Output value.
	plist)
    (mapc (lambda (cell)
	    (setq plist (plist-put plist (car cell) (eval (nth 3 cell)))))
	  all)
    ;; Return value.
    plist))

(defun org-export-initial-options ()
  "Return a plist with properties related to input buffer."
  (let ((visited-file (buffer-file-name (buffer-base-buffer))))
    (list
     ;; Store full path of input file name, or nil.  For internal use.
     :input-file visited-file
     ;; `:macro-date', `:macro-time' and `:macro-property' could as well
     ;; be initialized as tree properties, since they don't depend on
     ;; initial environment.  Though, it may be more logical to keep
     ;; them close to other ":macro-" properties.
     :macro-date "(eval (format-time-string \"$1\"))"
     :macro-time "(eval (format-time-string \"$1\"))"
     :macro-property "(eval (org-entry-get nil \"$1\" 'selective))"
     :macro-modification-time
     (and visited-file
	  (file-exists-p visited-file)
	  (concat "(eval (format-time-string \"$1\" '"
		  (prin1-to-string (nth 5 (file-attributes visited-file)))
		  "))"))
     ;; Store input file name as a macro.
     :macro-input-file (and visited-file (file-name-nondirectory visited-file))
     ;; Footnotes definitions must be collected in the original buffer,
     ;; as there's no insurance that they will still be in the parse
     ;; tree, due to some narrowing.
     :footnote-definition-alist
     (let (alist)
       (org-with-wide-buffer
	(goto-char (point-min))
	(while (re-search-forward org-footnote-definition-re nil t)
	  (let ((def (org-footnote-at-definition-p)))
	    (when def
	      (org-skip-whitespace)
	      (push (cons (car def)
			  (save-restriction
			    (narrow-to-region (point) (nth 2 def))
			    ;; Like `org-element-parse-buffer', but
			    ;; makes sure the definition doesn't start
			    ;; with a section element.
			    (nconc
			     (list 'org-data nil)
			     (org-element-parse-elements
			      (point-min) (point-max) nil nil nil nil nil))))
		    alist))))
	alist)))))

(defvar org-export-allow-BIND-local nil)
(defun org-export-confirm-letbind ()
  "Can we use #+BIND values during export?
By default this will ask for confirmation by the user, to divert
possible security risks."
  (cond
   ((not org-export-allow-BIND) nil)
   ((eq org-export-allow-BIND t) t)
   ((local-variable-p 'org-export-allow-BIND-local) org-export-allow-BIND-local)
   (t (org-set-local 'org-export-allow-BIND-local
		     (yes-or-no-p "Allow BIND values in this buffer? ")))))

(defun org-export-install-letbind-maybe ()
  "Install the values from #+BIND lines as local variables.
Variables must be installed before in-buffer options are
retrieved."
  (let (letbind pair)
    (org-with-wide-buffer
     (goto-char (point-min))
     (while (re-search-forward (org-make-options-regexp '("BIND")) nil t)
       (when (org-export-confirm-letbind)
	 (push (read (concat "(" (org-match-string-no-properties 2) ")"))
	       letbind))))
    (while (setq pair (pop letbind))
      (org-set-local (car pair) (nth 1 pair)))))


;;;; Tree Properties

;; Tree properties are infromation extracted from parse tree.  They
;; are initialized at the beginning of the transcoding process by
;; `org-export-collect-tree-properties'.

;; Dedicated functions focus on computing the value of specific tree
;; properties during initialization.  Thus,
;; `org-export-populate-ignore-list' lists elements and objects that
;; should be skipped during export, `org-export-get-min-level' gets
;; the minimal exportable level, used as a basis to compute relative
;; level for headlines.  Eventually
;; `org-export-collect-headline-numbering' builds an alist between
;; headlines and their numbering.

(defun org-export-collect-tree-properties (data info backend)
  "Extract tree properties from parse tree.

DATA is the parse tree from which information is retrieved.  INFO
is a list holding export options.  BACKEND is the back-end called
for transcoding, as a symbol.

Following tree properties are set:
`:back-end'        Back-end used for transcoding.

`:headline-offset' Offset between true level of headlines and
		   local level.  An offset of -1 means an headline
		   of level 2 should be considered as a level
		   1 headline in the context.

`:headline-numbering' Alist of all headlines as key an the
		      associated numbering as value.

`:ignore-list'     List of elements that should be ignored during
                   export.

`:parse-tree'      Whole parse tree.

`:target-list'     List of all targets in the parse tree."
  ;; First, get the list of elements and objects to ignore, and put it
  ;; into `:ignore-list'.  Do not overwrite any user ignore that might
  ;; have been done during parse tree filtering.
  (setq info
	(plist-put info
		   :ignore-list
		   (append (org-export-populate-ignore-list data info)
			   (plist-get info :ignore-list))))
  ;; Then compute `:headline-offset' in order to be able to use
  ;; `org-export-get-relative-level'.
  (setq info
	(plist-put info
		   :headline-offset (- 1 (org-export-get-min-level data info))))
  ;; Now, properties order doesn't matter: get the rest of the tree
  ;; properties.
  (nconc
   `(:parse-tree
     ,data
     :target-list
     ,(org-element-map
       data '(keyword target)
       (lambda (blob)
	 (when (or (eq (org-element-type blob) 'target)
		   (string= (upcase (org-element-property :key blob))
                            "TARGET"))
	   blob)) info)
     :headline-numbering ,(org-export-collect-headline-numbering data info)
     :back-end ,backend)
   info))

(defun org-export-get-min-level (data options)
  "Return minimum exportable headline's level in DATA.
DATA is parsed tree as returned by `org-element-parse-buffer'.
OPTIONS is a plist holding export options."
  (catch 'exit
    (let ((min-level 10000))
      (mapc
       (lambda (blob)
	 (when (and (eq (org-element-type blob) 'headline)
		    (not (member blob (plist-get options :ignore-list))))
	   (setq min-level
		 (min (org-element-property :level blob) min-level)))
	 (when (= min-level 1) (throw 'exit 1)))
       (org-element-contents data))
      ;; If no headline was found, for the sake of consistency, set
      ;; minimum level to 1 nonetheless.
      (if (= min-level 10000) 1 min-level))))

(defun org-export-collect-headline-numbering (data options)
  "Return numbering of all exportable headlines in a parse tree.

DATA is the parse tree.  OPTIONS is the plist holding export
options.

Return an alist whose key is an headline and value is its
associated numbering \(in the shape of a list of numbers\)."
  (let ((numbering (make-vector org-export-max-depth 0)))
    (org-element-map
     data
     'headline
     (lambda (headline)
       (let ((relative-level
	      (1- (org-export-get-relative-level headline options))))
	 (cons
	  headline
	  (loop for n across numbering
		for idx from 0 to org-export-max-depth
		when (< idx relative-level) collect n
		when (= idx relative-level) collect (aset numbering idx (1+ n))
		when (> idx relative-level) do (aset numbering idx 0)))))
     options)))

(defun org-export-populate-ignore-list (data options)
  "Return list of elements and objects to ignore during export.

DATA is the parse tree to traverse.  OPTIONS is the plist holding
export options.

Return elements or objects to ignore as a list."
  (let (ignore
	(walk-data
	 (function
	  (lambda (data options selected)
	    ;; Collect ignored elements or objects into IGNORE-LIST.
	    (mapc
	     (lambda (el)
	       (if (org-export--skip-p el options selected) (push el ignore)
		 (let ((type (org-element-type el)))
		   (if (and (eq (plist-get info :with-archived-trees) 'headline)
			    (eq (org-element-type el) 'headline)
			    (org-element-property :archivedp el))
		       ;; If headline is archived but tree below has
		       ;; to be skipped, add it to ignore list.
		       (mapc (lambda (e) (push e ignore))
			     (org-element-contents el))
		     ;; Move into recursive objects/elements.
		     (when (or (eq type 'org-data)
			       (memq type org-element-greater-elements)
			       (memq type org-element-recursive-objects)
			       (eq type 'paragraph))
		       (funcall walk-data el options selected))))))
	     (org-element-contents data))))))
    ;; Main call.  First find trees containing a select tag, if any.
    (funcall walk-data data options (org-export--selected-trees data options))
    ;; Return value.
    ignore))

(defun org-export--selected-trees (data info)
  "Return list of headlines containing a select tag in their tree.
DATA is parsed data as returned by `org-element-parse-buffer'.
INFO is a plist holding export options."
  (let (selected-trees
	(walk-data
	 (function
	  (lambda (data genealogy)
	    (case (org-element-type data)
	      (org-data
	       (funcall walk-data (org-element-contents data) genealogy))
	      (headline
	       (let ((tags (org-element-property :tags headline)))
		 (if (and tags
			  (loop for tag in (plist-get info :select-tags)
				thereis (string-match
					 (format ":%s:" tag) tags)))
		     ;; When a select tag is found, mark as acceptable
		     ;; full genealogy and every headline within the
		     ;; tree.
		     (setq selected-trees
			   (append
			    (cons data genealogy)
			    (org-element-map data 'headline 'identity)
			    selected-trees))
		   ;; Else, continue searching in tree, recursively.
		   (funcall walk-data data (cons data genealogy))))))))))
    (funcall walk-data data nil) selected-trees))

(defun org-export--skip-p (blob options select-tags)
  "Non-nil when element or object BLOB should be skipped during export.
OPTIONS is the plist holding export options."
  (case (org-element-type blob)
    ;; Check headline.
    (headline
     (let ((with-tasks (plist-get options :with-tasks))
	   (todo (org-element-property :todo-keyword blob))
	   (todo-type (org-element-property :todo-type blob))
	   (archived (plist-get options :with-archived-trees))
	   (tag-list (let ((tags (org-element-property :tags blob)))
		       (and tags (org-split-string tags ":")))))
       (or
	;; Ignore subtrees with an exclude tag.
	(loop for k in (plist-get options :exclude-tags)
	      thereis (member k tag-list))
	;; Ignore subtrees without a select tag, when such tag is
	;; found in the buffer.
	(member blob select-tags)
	;; Ignore commented sub-trees.
	(org-element-property :commentedp blob)
	;; Ignore archived subtrees if `:with-archived-trees' is nil.
	(and (not archived) (org-element-property :archivedp blob))
	;; Ignore tasks, if specified by `:with-tasks' property.
	(and todo
	     (or (not with-tasks)
		 (and (memq with-tasks '(todo done))
		      (not (eq todo-type with-tasks)))
		 (and (consp with-tasks) (not (member todo with-tasks))))))))
    ;; Check time-stamp.
    (time-stamp (not (plist-get options :with-timestamps)))
    ;; Check drawer.
    (drawer
     (or (not (plist-get options :with-drawers))
	 (and (consp (plist-get options :with-drawers))
	      (not (member (org-element-property :drawer-name blob)
			   (plist-get options :with-drawers))))))))


\f
;;; The Transcoder

;; This function reads Org data (obtained with, i.e.
;; `org-element-parse-buffer') and transcodes it into a specified
;; back-end output.  It takes care of updating local properties,
;; filtering out elements or objects according to export options and
;; organizing the output blank lines and white space are preserved.

;; Though, this function is inapropriate for secondary strings, which
;; require a fresh copy of the plist passed as INFO argument.  Thus,
;; `org-export-secondary-string' is provided for that specific task.

;; Internally, three functions handle the filtering of objects and
;; elements during the export.  In particular,
;; `org-export-ignore-element' mark an element or object so future
;; parse tree traversals skip it, `org-export-interpret-p' tells which
;; elements or objects should be seen as real Org syntax and
;; `org-export-expand' transforms the others back into their original
;; shape.

(defun org-export-data (data backend info)
  "Convert DATA to a string into BACKEND format.

DATA is a nested list as returned by `org-element-parse-buffer'.

BACKEND is a symbol among supported exporters.

INFO is a plist holding export options and also used as
a communication channel between elements when walking the nested
list.  See `org-export-update-info' function for more
details.

Return transcoded string."
  (mapconcat
   ;; BLOB can be an element, an object, a string, or nil.
   (lambda (blob)
     (cond
      ((not blob) nil)
      ;; BLOB is a string.  Check if the optional transcoder for plain
      ;; text exists, and call it in that case.  Otherwise, simply
      ;; return string.  Also update INFO and call
      ;; `org-export-filter-plain-text-functions'.
      ((stringp blob)
       (let ((transcoder (intern (format "org-%s-plain-text" backend))))
	 (org-export-filter-apply-functions
	  (plist-get info :filter-plain-text)
	  (if (fboundp transcoder) (funcall transcoder blob info) blob)
	  backend info)))
      ;; BLOB is an element or an object.
      (t
       (let* ((type (org-element-type blob))
	      ;; 1. Determine the appropriate TRANSCODER.
	      (transcoder
	       (cond
		;; 1.0 A full Org document is inserted.
		((eq type 'org-data) 'identity)
		;; 1.1. BLOB should be ignored.
		((member blob (plist-get info :ignore-list)) nil)
		;; 1.2. BLOB shouldn't be transcoded.  Interpret it
		;;      back into Org syntax.
		((not (org-export-interpret-p blob info)) 'org-export-expand)
		;; 1.3. Else apply naming convention.
		(t (let ((trans (intern (format "org-%s-%s" backend type))))
		     (and (fboundp trans) trans)))))
	      ;; 2. Compute CONTENTS of BLOB.
	      (contents
	       (cond
		;; Case 0. No transcoder defined: ignore BLOB.
		((not transcoder) nil)
		;; Case 1. Transparently export an Org document.
		((eq type 'org-data) (org-export-data blob backend info))
		;; Case 2. For a recursive object.
		((memq type org-element-recursive-objects)
		 (org-export-data blob backend info))
		;; Case 3. For a recursive element.
		((memq type org-element-greater-elements)
		 ;; Ignore contents of an archived tree
		 ;; when `:with-archived-trees' is `headline'.
		 (unless (and
			  (eq type 'headline)
			  (eq (plist-get info :with-archived-trees) 'headline)
			  (org-element-property :archivedp blob))
		   (org-element-normalize-string
		    (org-export-data blob backend info))))
		;; Case 4. For a paragraph.
		((eq type 'paragraph)
		 (let ((paragraph
			(org-element-normalize-contents
			 blob
			 ;; When normalizing contents of an item or
			 ;; a footnote definition, ignore first line's
			 ;; indentation: there is none and it might be
			 ;; misleading.
			 (and (not (org-export-get-previous-element blob info))
			      (let ((parent (org-export-get-parent blob info)))
				(memq (org-element-type parent)
				      '(footnote-definition item)))))))
		   (org-export-data paragraph backend info)))))
	      ;; 3. Transcode BLOB into RESULTS string.
	      (results (cond
			((not transcoder) nil)
			((eq transcoder 'org-export-expand)
			 (org-export-data
			  `(org-data nil ,(funcall transcoder blob contents))
			  backend info))
			(t (funcall transcoder blob contents info)))))
	 ;; 4. Return results.
	 (cond
	  ((not results) nil)
	  ;; No filter for a full document.
	  ((eq type 'org-data) results)
	  ;; Otherwise, update INFO, append the same white space
	  ;; between elements or objects as in the original buffer,
	  ;; and call appropriate filters.
	  (t
	   (let ((results
		  (org-export-filter-apply-functions
		   (plist-get info (intern (format ":filter-%s" type)))
		   (let ((post-blank (org-element-property :post-blank blob)))
		     (if (memq type org-element-all-elements)
			 (concat (org-element-normalize-string results)
				 (make-string post-blank ?\n))
		       (concat results (make-string post-blank ? ))))
		   backend info)))
	     ;; Eventually return string.
	     results)))))))
   (org-element-contents data) ""))

(defun org-export-secondary-string (secondary backend info)
  "Convert SECONDARY string into BACKEND format.

SECONDARY is a nested list as returned by
`org-element-parse-secondary-string'.

BACKEND is a symbol among supported exporters.  INFO is a plist
used as a communication channel.

Return transcoded string."
  ;; Make SECONDARY acceptable for `org-export-data'.
  (let ((s (if (listp secondary) secondary (list secondary))))
    (org-export-data `(org-data nil ,@s) backend (copy-sequence info))))

(defun org-export-interpret-p (blob info)
  "Non-nil if element or object BLOB should be interpreted as Org syntax.
Check is done according to export options INFO, stored as
a plist."
  (case (org-element-type blob)
    ;; ... entities...
    (entity (plist-get info :with-entities))
    ;; ... emphasis...
    (emphasis (plist-get info :with-emphasize))
    ;; ... fixed-width areas.
    (fixed-width (plist-get info :with-fixed-width))
    ;; ... footnotes...
    ((footnote-definition footnote-reference)
     (plist-get info :with-footnotes))
    ;; ... sub/superscripts...
    ((subscript superscript)
     (let ((sub/super-p (plist-get info :with-sub-superscript)))
       (if (eq sub/super-p '{})
	   (org-element-property :use-brackets-p blob)
	 sub/super-p)))
    ;; ... tables...
    (table (plist-get info :with-tables))
    (otherwise t)))

(defsubst org-export-expand (blob contents)
  "Expand a parsed element or object to its original state.
BLOB is either an element or an object.  CONTENTS is its
contents, as a string or nil."
  (funcall (intern (format "org-element-%s-interpreter" (org-element-type blob)))
	   blob contents))

(defun org-export-ignore-element (element info)
  "Add ELEMENT to `:ignore-list' in INFO.

Any element in `:ignore-list' will be skipped when using
`org-element-map'.  INFO is modified by side effects."
  (plist-put info :ignore-list (cons element (plist-get info :ignore-list))))


\f
;;; The Filter System

;; Filters allow end-users to tweak easily the transcoded output.
;; They are the functional counterpart of hooks, as every filter in
;; a set is applied to the return value of the previous one.

;; Every set is back-end agnostic.  Although, a filter is always
;; called, in addition to the string it applies to, with the back-end
;; used as argument, so it's easy enough for the end-user to add
;; back-end specific filters in the set.  The communication channel,
;; as a plist, is required as the third argument.

;; Filters sets are defined below. There are of four types:

;; - `org-export-filter-parse-tree-functions' applies directly on the
;;   complete parsed tree.  It's the only filters set that doesn't
;;   apply to a string.
;; - `org-export-filter-final-output-functions' applies to the final
;;   transcoded string.
;; - `org-export-filter-plain-text-functions' applies to any string
;;   not recognized as Org syntax.
;; - `org-export-filter-TYPE-functions' applies on the string returned
;;   after an element or object of type TYPE has been transcoded.

;; All filters sets are applied through
;; `org-export-filter-apply-functions' function.  Filters in a set are
;; applied in a LIFO fashion.  It allows developers to be sure that
;; their filters will be applied first.

;; Filters properties are installed in communication channel just
;; before parsing, with `org-export-install-filters' function.

;;;; Special Filters
(defvar org-export-filter-parse-tree-functions nil
  "Filter, or list of filters, applied to the parsed tree.
Each filter is called with three arguments: the parse tree, as
returned by `org-element-parse-buffer', the back-end, as
a symbol, and the communication channel, as a plist.  It must
return the modified parse tree to transcode.")

(defvar org-export-filter-final-output-functions nil
  "Filter, or list of filters, applied to the transcoded string.
Each filter is called with three arguments: the full transcoded
string, the back-end, as a symbol, and the communication channel,
as a plist.  It must return a string that will be used as the
final export output.")

(defvar org-export-filter-plain-text-functions nil
  "Filter, or list of filters, applied to plain text.
Each filter is called with three arguments: a string which
contains no Org syntax, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")


;;;; Elements Filters

(defvar org-export-filter-center-block-functions nil
  "List of functions applied to a transcoded center block.
Each filter is called with three arguments: the transcoded center
block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-drawer-functions nil
  "List of functions applied to a transcoded drawer.
Each filter is called with three arguments: the transcoded
drawer, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-dynamic-block-functions nil
  "List of functions applied to a transcoded dynamic-block.
Each filter is called with three arguments: the transcoded
dynamic-block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-headline-functions nil
  "List of functions applied to a transcoded headline.
Each filter is called with three arguments: the transcoded
headline, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-inlinetask-functions nil
  "List of functions applied to a transcoded inlinetask.
Each filter is called with three arguments: the transcoded
inlinetask, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-plain-list-functions nil
  "List of functions applied to a transcoded plain-list.
Each filter is called with three arguments: the transcoded
plain-list, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-item-functions nil
  "List of functions applied to a transcoded item.
Each filter is called with three arguments: the transcoded item,
as a string, the back-end, as a symbol, and the communication
channel, as a plist.  It must return a string or nil.")

(defvar org-export-filter-comment-functions nil
  "List of functions applied to a transcoded comment.
Each filter is called with three arguments: the transcoded
comment, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-comment-block-functions nil
  "List of functions applied to a transcoded comment-comment.
Each filter is called with three arguments: the transcoded
comment-block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-example-block-functions nil
  "List of functions applied to a transcoded example-block.
Each filter is called with three arguments: the transcoded
example-block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-export-block-functions nil
  "List of functions applied to a transcoded export-block.
Each filter is called with three arguments: the transcoded
export-block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-fixed-width-functions nil
  "List of functions applied to a transcoded fixed-width.
Each filter is called with three arguments: the transcoded
fixed-width, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-footnote-definition-functions nil
  "List of functions applied to a transcoded footnote-definition.
Each filter is called with three arguments: the transcoded
footnote-definition, as a string, the back-end, as a symbol, and
the communication channel, as a plist.  It must return a string
or nil.")

(defvar org-export-filter-horizontal-rule-functions nil
  "List of functions applied to a transcoded horizontal-rule.
Each filter is called with three arguments: the transcoded
horizontal-rule, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-keyword-functions nil
  "List of functions applied to a transcoded keyword.
Each filter is called with three arguments: the transcoded
keyword, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-latex-environment-functions nil
  "List of functions applied to a transcoded latex-environment.
Each filter is called with three arguments: the transcoded
latex-environment, as a string, the back-end, as a symbol, and
the communication channel, as a plist.  It must return a string
or nil.")

(defvar org-export-filter-babel-call-functions nil
  "List of functions applied to a transcoded babel-call.
Each filter is called with three arguments: the transcoded
babel-call, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-paragraph-functions nil
  "List of functions applied to a transcoded paragraph.
Each filter is called with three arguments: the transcoded
paragraph, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-property-drawer-functions nil
  "List of functions applied to a transcoded property-drawer.
Each filter is called with three arguments: the transcoded
property-drawer, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-quote-block-functions nil
  "List of functions applied to a transcoded quote block.
Each filter is called with three arguments: the transcoded quote
block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-quote-section-functions nil
  "List of functions applied to a transcoded quote-section.
Each filter is called with three arguments: the transcoded
quote-section, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-section-functions nil
  "List of functions applied to a transcoded section.
Each filter is called with three arguments: the transcoded
section, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-special-block-functions nil
  "List of functions applied to a transcoded special block.
Each filter is called with three arguments: the transcoded
special block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-src-block-functions nil
  "List of functions applied to a transcoded src-block.
Each filter is called with three arguments: the transcoded
src-block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-table-functions nil
  "List of functions applied to a transcoded table.
Each filter is called with three arguments: the transcoded table,
as a string, the back-end, as a symbol, and the communication
channel, as a plist.  It must return a string or nil.")

(defvar org-export-filter-verse-block-functions nil
  "List of functions applied to a transcoded verse block.
Each filter is called with three arguments: the transcoded verse
block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")


;;;; Objects Filters

(defvar org-export-filter-emphasis-functions nil
  "List of functions applied to a transcoded emphasis.
Each filter is called with three arguments: the transcoded
emphasis, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-entity-functions nil
  "List of functions applied to a transcoded entity.
Each filter is called with three arguments: the transcoded
entity, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-export-snippet-functions nil
  "List of functions applied to a transcoded export-snippet.
Each filter is called with three arguments: the transcoded
export-snippet, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-footnote-reference-functions nil
  "List of functions applied to a transcoded footnote-reference.
Each filter is called with three arguments: the transcoded
footnote-reference, as a string, the back-end, as a symbol, and
the communication channel, as a plist.  It must return a string
or nil.")

(defvar org-export-filter-inline-babel-call-functions nil
  "List of functions applied to a transcoded inline-babel-call.
Each filter is called with three arguments: the transcoded
inline-babel-call, as a string, the back-end, as a symbol, and
the communication channel, as a plist.  It must return a string
or nil.")

(defvar org-export-filter-inline-src-block-functions nil
  "List of functions applied to a transcoded inline-src-block.
Each filter is called with three arguments: the transcoded
inline-src-block, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-latex-fragment-functions nil
  "List of functions applied to a transcoded latex-fragment.
Each filter is called with three arguments: the transcoded
latex-fragment, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-line-break-functions nil
  "List of functions applied to a transcoded line-break.
Each filter is called with three arguments: the transcoded
line-break, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-link-functions nil
  "List of functions applied to a transcoded link.
Each filter is called with three arguments: the transcoded link,
as a string, the back-end, as a symbol, and the communication
channel, as a plist.  It must return a string or nil.")

(defvar org-export-filter-macro-functions nil
  "List of functions applied to a transcoded macro.
Each filter is called with three arguments: the transcoded macro,
as a string, the back-end, as a symbol, and the communication
channel, as a plist.  It must return a string or nil.")

(defvar org-export-filter-radio-target-functions nil
  "List of functions applied to a transcoded radio-target.
Each filter is called with three arguments: the transcoded
radio-target, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-statistics-cookie-functions nil
  "List of functions applied to a transcoded statistics-cookie.
Each filter is called with three arguments: the transcoded
statistics-cookie, as a string, the back-end, as a symbol, and
the communication channel, as a plist.  It must return a string
or nil.")

(defvar org-export-filter-subscript-functions nil
  "List of functions applied to a transcoded subscript.
Each filter is called with three arguments: the transcoded
subscript, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-superscript-functions nil
  "List of functions applied to a transcoded superscript.
Each filter is called with three arguments: the transcoded
superscript, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-target-functions nil
  "List of functions applied to a transcoded target.
Each filter is called with three arguments: the transcoded
target, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-time-stamp-functions nil
  "List of functions applied to a transcoded time-stamp.
Each filter is called with three arguments: the transcoded
time-stamp, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defvar org-export-filter-verbatim-functions nil
  "List of functions applied to a transcoded verbatim.
Each filter is called with three arguments: the transcoded
verbatim, as a string, the back-end, as a symbol, and the
communication channel, as a plist.  It must return a string or
nil.")

(defun org-export-filter-apply-functions (filters value backend info)
  "Call every function in FILTERS with arguments VALUE, BACKEND and INFO.
Functions are called in a LIFO fashion, to be sure that developer
specified filters, if any, are called first."
  (loop for filter in filters
	if (not value) return nil else
	do (setq value (funcall filter value backend info)))
  value)

(defun org-export-install-filters (backend info)
  "Install filters properties in communication channel.

BACKEND is a symbol specifying which back-end specific filters to
install, if any.  INFO is a plist containing the current
communication channel.

Return the updated communication channel."
  (let (plist)
    ;; Install user defined filters with `org-export-filters-alist'.
    (mapc (lambda (p)
	    (setq plist (plist-put plist (car p) (eval (cdr p)))))
	  org-export-filters-alist)
    ;; Prepend back-end specific filters to that list.
    (let ((back-end-filters (intern (format "org-%s-filters-alist" backend))))
      (when (boundp back-end-filters)
	(mapc (lambda (p)
		;; Single values get consed, lists are prepended.
		(let ((key (car p)) (value (cdr p)))
		  (when value
		    (setq plist
			  (plist-put
			   plist key
			   (if (atom value) (cons value (plist-get plist key))
			     (append value (plist-get plist key))))))))
	      (eval back-end-filters))))
    ;; Return new communication channel.
    (org-combine-plists info plist)))


\f
;;; Core functions

;; This is the room for the main function, `org-export-as', along with
;; its derivatives, `org-export-to-buffer' and `org-export-to-file'.
;; They differ only by the way they output the resulting code.

;; `org-export-output-file-name' is an auxiliary function meant to be
;; used with `org-export-to-file'.  With a given extension, it tries
;; to provide a canonical file name to write export output to.

;; Note that `org-export-as' doesn't really parse the current buffer,
;; but a copy of it (with the same buffer-local variables and
;; visibility), where include keywords are expanded and Babel blocks
;; are executed, if appropriate.
;; `org-export-with-current-buffer-copy' macro prepares that copy.

;; File inclusion is taken care of by
;; `org-export-expand-include-keyword' and
;; `org-export-prepare-file-contents'.  Structure wise, including
;; a whole Org file in a buffer often makes little sense.  For
;; example, if the file contains an headline and the include keyword
;; was within an item, the item should contain the headline.  That's
;; why file inclusion should be done before any structure can be
;; associated to the file, that is before parsing.

(defun org-export-as
  (backend &optional subtreep visible-only body-only ext-plist noexpand)
  "Transcode current Org buffer into BACKEND code.

If narrowing is active in the current buffer, only transcode its
narrowed part.

If a region is active, transcode that region.

When optional argument SUBTREEP is non-nil, transcode the
sub-tree at point, extracting information from the headline
properties first.

When optional argument VISIBLE-ONLY is non-nil, don't export
contents of hidden elements.

When optional argument BODY-ONLY is non-nil, only return body
code, without preamble nor postamble.

Optional argument EXT-PLIST, when provided, is a property list
with external parameters overriding Org default settings, but
still inferior to file-local settings.

Optional argument NOEXPAND, when non-nil, prevents included files
to be expanded and Babel code to be executed.

Return code as a string."
  (save-excursion
    (save-restriction
      ;; Narrow buffer to an appropriate region for parsing.
      (cond ((org-region-active-p)
	     (narrow-to-region (region-beginning) (region-end)))
	    (subtreep (org-narrow-to-subtree)))
      ;; Retrieve export options (INFO) and parsed tree (RAW-DATA),
      ;; Then options can be completed with tree properties.  Note:
      ;; Buffer isn't parsed directly.  Instead, a temporary copy is
      ;; created, where include keywords are expanded and code blocks
      ;; are evaluated.  RAW-DATA is the parsed tree of the buffer
      ;; resulting from that process.  Eventually call
      ;; `org-export-filter-parse-tree-functions'.
      (goto-char (point-min))
      (let ((info (org-export-get-environment backend subtreep ext-plist)))
	;; Remove subtree's headline from contents if subtree mode is
	;; activated.
	(when subtreep (forward-line) (narrow-to-region (point) (point-max)))
	;; Install filters in communication channel.
	(setq info (org-export-install-filters backend info))
	(let ((raw-data
	       (org-export-filter-apply-functions
		(plist-get info :filter-parse-tree)
		;; If NOEXPAND is non-nil, simply parse current
		;; visible part of buffer.
		(if noexpand (org-element-parse-buffer nil visible-only)
		  (org-export-with-current-buffer-copy
		   (org-export-expand-include-keyword)
		   (let ((org-current-export-file (current-buffer)))
		     (org-export-blocks-preprocess))
		   (org-element-parse-buffer nil visible-only)))
		backend info)))
	;; Complete communication channel with tree properties.
	(setq info
	      (org-combine-plists
	       info
	       (org-export-collect-tree-properties raw-data info backend)))
	;; Transcode RAW-DATA.  Also call
	;; `org-export-filter-final-output-functions'.
	(let* ((body (org-element-normalize-string
		      (org-export-data raw-data backend info)))
	       (template (intern (format "org-%s-template" backend)))
	       (output (org-export-filter-apply-functions
			(plist-get info :filter-final-output)
			(if (or (not (fboundp template)) body-only) body
			  (funcall template body info))
			backend info)))
	  ;; Maybe add final OUTPUT to kill ring before returning it.
	  (when org-export-copy-to-kill-ring (org-kill-new output))
	  output))))))

(defun org-export-to-buffer
  (backend buffer &optional subtreep visible-only body-only ext-plist noexpand)
  "Call `org-export-as' with output to a specified buffer.

BACKEND is the back-end used for transcoding, as a symbol.

BUFFER is the output buffer.  If it already exists, it will be
erased first, otherwise, it will be created.

Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
and NOEXPAND are similar to those used in `org-export-as', which
see.

Return buffer."
  (let ((out (org-export-as
	      backend subtreep visible-only body-only ext-plist noexpand))
	(buffer (get-buffer-create buffer)))
    (with-current-buffer buffer
      (erase-buffer)
      (insert out)
      (goto-char (point-min)))
    buffer))

(defun org-export-to-file
  (backend file &optional subtreep visible-only body-only ext-plist noexpand)
  "Call `org-export-as' with output to a specified file.

BACKEND is the back-end used for transcoding, as a symbol.  FILE
is the name of the output file, as a string.

Optional arguments SUBTREEP, VISIBLE-ONLY, BODY-ONLY, EXT-PLIST
and NOEXPAND are similar to those used in `org-export-as', which
see.

Return output file's name."
  ;; Checks for FILE permissions.  `write-file' would do the same, but
  ;; we'd rather avoid needless transcoding of parse tree.
  (unless (file-writable-p file) (error "Output file not writable"))
  ;; Insert contents to a temporary buffer and write it to FILE.
  (let ((out (org-export-as
	      backend subtreep visible-only body-only ext-plist noexpand)))
    (with-temp-buffer
      (insert out)
      (let ((coding-system-for-write org-export-coding-system))
	(write-file file))))
  ;; Return full path.
  file)

(defun org-export-output-file-name (extension &optional subtreep pub-dir)
  "Return output file's name according to buffer specifications.

EXTENSION is a string representing the output file extension,
with the leading dot.

With a non-nil optional argument SUBTREEP, try to determine
output file's name by looking for \"EXPORT_FILE_NAME\" property
of subtree at point.

When optional argument PUB-DIR is set, use it as the publishing
directory.

Return file name as a string, or nil if it couldn't be
determined."
  (let ((base-name
	 ;; File name may come from EXPORT_FILE_NAME subtree property,
	 ;; assuming point is at beginning of said sub-tree.
	 (file-name-sans-extension
	  (or (and subtreep
		   (org-entry-get
		    (save-excursion
		      (ignore-errors
			(org-back-to-heading (not visible-only)) (point)))
		    "EXPORT_FILE_NAME" t))
	      ;; File name may be extracted from buffer's associated
	      ;; file, if any.
	      (buffer-file-name (buffer-base-buffer))
	      ;; Can't determine file name on our own: Ask user.
	      (let ((read-file-name-function
		     (and org-completion-use-ido 'ido-read-file-name)))
		(read-file-name
		 "Output file: " pub-dir nil nil nil
		 (lambda (name)
		   (string= (file-name-extension name t) extension))))))))
    ;; Build file name. Enforce EXTENSION over whatever user may have
    ;; come up with. PUB-DIR, if defined, always has precedence over
    ;; any provided path.
    (cond
     (pub-dir
      (concat (file-name-as-directory pub-dir)
	      (file-name-nondirectory base-name)
	      extension))
     ((string= (file-name-nondirectory base-name) base-name)
      (concat (file-name-as-directory ".") base-name extension))
     (t (concat base-name extension)))))

(defmacro org-export-with-current-buffer-copy (&rest body)
  "Apply BODY in a copy of the current buffer.

The copy preserves local variables and visibility of the original
buffer.

Point is at buffer's beginning when BODY is applied."
  (org-with-gensyms (original-buffer offset buffer-string overlays)
    `(let ((,original-buffer ,(current-buffer))
	   (,offset ,(1- (point-min)))
	   (,buffer-string ,(buffer-string))
	   (,overlays (mapcar
		       'copy-overlay (overlays-in (point-min) (point-max)))))
       (with-temp-buffer
	 (let ((buffer-invisibility-spec nil))
	   (org-clone-local-variables
	    ,original-buffer
	    "^\\(org-\\|orgtbl-\\|major-mode$\\|outline-\\(regexp\\|level\\)$\\)")
	   (insert ,buffer-string)
	   (mapc (lambda (ov)
		   (move-overlay
		    ov
		    (- (overlay-start ov) ,offset)
		    (- (overlay-end ov) ,offset)
		    (current-buffer)))
		 ,overlays)
	   (goto-char (point-min))
	   (progn ,@body))))))
(def-edebug-spec org-export-with-current-buffer-copy (body))

(defun org-export-expand-include-keyword (&optional included dir)
  "Expand every include keyword in buffer.
Optional argument INCLUDED is a list of included file names along
with their line restriction, when appropriate.  It is used to
avoid infinite recursion.  Optional argument DIR is the current
working directory.  It is used to properly resolve relative
paths."
  (let ((case-fold-search t))
    (goto-char (point-min))
    (while (re-search-forward "^[ \t]*#\\+INCLUDE: \\(.*\\)" nil t)
      (when (eq (org-element-type (save-match-data (org-element-at-point)))
		'keyword)
	(beginning-of-line)
	;; Extract arguments from keyword's value.
	(let* ((value (match-string 1))
	       (ind (org-get-indentation))
	       (file (and (string-match "^\"\\(\\S-+\\)\"" value)
			  (prog1 (expand-file-name (match-string 1 value) dir)
			    (setq value (replace-match "" nil nil value)))))
	       (lines
		(and (string-match
		      ":lines +\"\\(\\(?:[0-9]+\\)?-\\(?:[0-9]+\\)?\\)\"" value)
		     (prog1 (match-string 1 value)
		       (setq value (replace-match "" nil nil value)))))
	       (env (cond ((string-match "\\<example\\>" value) 'example)
			  ((string-match "\\<src\\(?: +\\(.*\\)\\)?" value)
			   (match-string 1 value))))
	       ;; Minimal level of included file defaults to the child
	       ;; level of the current headline, if any, or one.  It
	       ;; only applies is the file is meant to be included as
	       ;; an Org one.
	       (minlevel
		(and (not env)
		     (if (string-match ":minlevel +\\([0-9]+\\)" value)
			 (prog1 (string-to-number (match-string 1 value))
			   (setq value (replace-match "" nil nil value)))
		       (let ((cur (org-current-level)))
			 (if cur (1+ (org-reduced-level cur)) 1))))))
	  ;; Remove keyword.
	  (delete-region (point) (progn (forward-line) (point)))
	  (cond
	   ((not (file-readable-p file)) (error "Cannot include file %s" file))
	   ;; Check if files has already been parsed.  Look after
	   ;; inclusion lines too, as different parts of the same file
	   ;; can be included too.
	   ((member (list file lines) included)
	    (error "Recursive file inclusion: %s" file))
	   (t
	    (cond
	     ((eq env 'example)
	      (insert
	       (let ((ind-str (make-string ind ? ))
		     (contents
		      ;; Protect sensitive contents with commas.
		      (replace-regexp-in-string
		       "\\(^\\)\\([*]\\|[ \t]*#\\+\\)" ","
		       (org-export-prepare-file-contents file lines)
		       nil nil 1)))
		 (format "%s#+BEGIN_EXAMPLE\n%s%s#+END_EXAMPLE\n"
			 ind-str contents ind-str))))
	     ((stringp env)
	      (insert
	       (let ((ind-str (make-string ind ? ))
		     (contents
		      ;; Protect sensitive contents with commas.
		      (replace-regexp-in-string
		       (if (string= env "org") "\\(^\\)\\(.\\)"
			 "\\(^\\)\\([*]\\|[ \t]*#\\+\\)") ","
			 (org-export-prepare-file-contents file lines)
			 nil nil 1)))
		 (format "%s#+BEGIN_SRC %s\n%s%s#+END_SRC\n"
			 ind-str env contents ind-str))))
	     (t
	      (insert
	       (with-temp-buffer
		 (org-mode)
		 (insert
		  (org-export-prepare-file-contents file lines ind minlevel))
		 (org-export-expand-include-keyword
		  (cons (list file lines) included)
		  (file-name-directory file))
		 (buffer-string))))))))))))

(defun org-export-prepare-file-contents (file &optional lines ind minlevel)
  "Prepare the contents of FILE for inclusion and return them as a string.

When optional argument LINES is a string specifying a range of
lines, include only those lines.

Optional argument IND, when non-nil, is an integer specifying the
global indentation of returned contents.  Since its purpose is to
allow an included file to stay in the same environment it was
created \(i.e. a list item), it doesn't apply past the first
headline encountered.

Optional argument MINLEVEL, when non-nil, is an integer
specifying the level that any top-level headline in the included
file should have."
  (with-temp-buffer
    (insert-file-contents file)
    (when lines
      (let* ((lines (split-string lines "-"))
	     (lbeg (string-to-number (car lines)))
	     (lend (string-to-number (cadr lines)))
	     (beg (if (zerop lbeg) (point-min)
		    (goto-char (point-min))
		    (forward-line (1- lbeg))
		    (point)))
	     (end (if (zerop lend) (point-max)
		    (goto-char (point-min))
		    (forward-line (1- lend))
		    (point))))
	(narrow-to-region beg end)))
    ;; Remove blank lines at beginning and end of contents.  The logic
    ;; behind that removal is that blank lines around include keyword
    ;; override blank lines in included file.
    (goto-char (point-min))
    (org-skip-whitespace)
    (beginning-of-line)
    (delete-region (point-min) (point))
    (goto-char (point-max))
    (skip-chars-backward " \r\t\n")
    (forward-line)
    (delete-region (point) (point-max))
    ;; If IND is set, preserve indentation of include keyword until
    ;; the first headline encountered.
    (when ind
      (unless (eq major-mode 'org-mode) (org-mode))
      (goto-char (point-min))
      (let ((ind-str (make-string ind ? )))
	(while (not (or (eobp) (looking-at org-outline-regexp-bol)))
	  ;; Do not move footnote definitions out of column 0.
	  (unless (and (looking-at org-footnote-definition-re)
		       (eq (org-element-type (org-element-at-point))
			   'footnote-definition))
	    (insert ind-str))
	  (forward-line))))
    ;; When MINLEVEL is specified, compute minimal level for headlines
    ;; in the file (CUR-MIN), and remove stars to each headline so
    ;; that headlines with minimal level have a level of MINLEVEL.
    (when minlevel
      (unless (eq major-mode 'org-mode) (org-mode))
      (let ((levels (org-map-entries
		     (lambda () (org-reduced-level (org-current-level))))))
	(when levels
	  (let ((offset (- minlevel (apply 'min levels))))
	    (unless (zerop offset)
	      (when org-odd-levels-only (setq offset (* offset 2)))
	      ;; Only change stars, don't bother moving whole
	      ;; sections.
	      (org-map-entries
	       (lambda () (if (< offset 0) (delete-char (abs offset))
		       (insert (make-string offset ?*))))))))))
    (buffer-string)))

\f
;;; Tools For Back-Ends

;; A whole set of tools is available to help build new exporters.  Any
;; function general enough to have its use across many back-ends
;; should be added here.

;; As of now, functions operating on footnotes, headlines, links,
;; macros, references, src-blocks, tables and tables of contents are
;; implemented.

;;;; For Export Snippets

;; Every export snippet is transmitted to the back-end.  Though, the
;; latter will only retain one type of export-snippet, ignoring
;; others, based on the former's target back-end.  The function
;; `org-export-snippet-backend' returns that back-end for a given
;; export-snippet.

(defun org-export-snippet-backend (export-snippet)
  "Return EXPORT-SNIPPET targeted back-end as a symbol.
Translation, with `org-export-snippet-translation-alist', is
applied."
  (let ((back-end (org-element-property :back-end export-snippet)))
    (intern
     (or (cdr (assoc back-end org-export-snippet-translation-alist))
	 back-end))))


;;;; For Footnotes

;; `org-export-collect-footnote-definitions' is a tool to list
;; actually used footnotes definitions in the whole parse tree, or in
;; an headline, in order to add footnote listings throughout the
;; transcoded data.

;; `org-export-footnote-first-reference-p' is a predicate used by some
;; back-ends, when they need to attach the footnote definition only to
;; the first occurrence of the corresponding label.

;; `org-export-get-footnote-definition' and
;; `org-export-get-footnote-number' provide easier access to
;; additional information relative to a footnote reference.

(defun org-export-collect-footnote-definitions (data info)
  "Return an alist between footnote numbers, labels and definitions.

DATA is the parse tree from which definitions are collected.
INFO is the plist used as a communication channel.

Definitions are sorted by order of references.  They either
appear as Org data \(transcoded with `org-export-data'\) or as
a secondary string for inlined footnotes \(transcoded with
`org-export-secondary-string'\).  Unreferenced definitions are
ignored."
  (let (num-alist
	(collect-fn
	 (function
	  (lambda (data)
	    ;; Collect footnote number, label and definition in DATA.
	    (org-element-map
	     data 'footnote-reference
	     (lambda (fn)
	       (when (org-export-footnote-first-reference-p fn info)
		 (let ((def (org-export-get-footnote-definition fn info)))
		   (push
		    (list (org-export-get-footnote-number fn info)
			  (org-element-property :label fn)
			  def)
		    num-alist)
		   ;; Also search in definition for nested footnotes.
		  (when (eq (org-element-property :type fn) 'standard)
		    (funcall collect-fn def)))))
	     info)
	    ;; Return final value.
	    (reverse num-alist)))))
    (funcall collect-fn (plist-get info :parse-tree))))

(defun org-export-footnote-first-reference-p (footnote-reference info)
  "Non-nil when a footnote reference is the first one for its label.

FOOTNOTE-REFERENCE is the footnote reference being considered.
INFO is the plist used as a communication channel."
  (let ((label (org-element-property :label footnote-reference)))
    ;; Anonymous footnotes are always a first reference.
    (if (not label) t
      ;; Otherwise, return the first footnote with the same LABEL and
      ;; test if it is equal to FOOTNOTE-REFERENCE.
      (let ((search-refs
	     (function
	      (lambda (data)
		(org-element-map
		 data 'footnote-reference
		 (lambda (fn)
		   (cond
		    ((string= (org-element-property :label fn) label)
		     (throw 'exit fn))
		    ;; If FN isn't inlined, be sure to traverse its
		    ;; definition before resuming search.  See
		    ;; comments in `org-export-get-footnote-number'
		    ;; for more information.
		    ((eq (org-element-property :type fn) 'standard)
		     (funcall search-refs
			      (org-export-get-footnote-definition fn info)))))
		 info 'first-match)))))
	(equal (catch 'exit (funcall search-refs (plist-get info :parse-tree)))
	       footnote-reference)))))

(defun org-export-get-footnote-definition (footnote-reference info)
  "Return definition of FOOTNOTE-REFERENCE as parsed data.
INFO is the plist used as a communication channel."
  (let ((label (org-element-property :label footnote-reference)))
    (or (org-element-property :inline-definition footnote-reference)
        (cdr (assoc label (plist-get info :footnote-definition-alist))))))

(defun org-export-get-footnote-number (footnote info)
  "Return number associated to a footnote.

FOOTNOTE is either a footnote reference or a footnote definition.
INFO is the plist used as a communication channel."
  (let ((label (org-element-property :label footnote))
	seen-refs
	(search-ref
	 (function
	  (lambda (data)
	    ;; Search footnote references through DATA, filling
	    ;; SEEN-REFS along the way.
	    (org-element-map
	     data 'footnote-reference
	     (lambda (fn)
	       (let ((fn-lbl (org-element-property :label fn)))
		 (cond
		  ;; Anonymous footnote match: return number.
		  ((and (not fn-lbl) (equal fn footnote))
		   (throw 'exit (1+ (length seen-refs))))
		  ;; Labels match: return number.
		  ((and label (string= label fn-lbl))
		   (throw 'exit (1+ (length seen-refs))))
		  ;; Anonymous footnote: it's always a new one.  Also,
		  ;; be sure to return nil from the `cond' so
		  ;; `first-match' doesn't get us out of the loop.
		  ((not fn-lbl) (push 'inline seen-refs) nil)
		  ;; Label not seen so far: add it so SEEN-REFS.
		  ;;
		  ;; Also search for subsequent references in footnote
		  ;; definition so numbering following reading logic.
		  ;; Note that we don't have to care about inline
		  ;; definitions, since `org-element-map' already
		  ;; traverse them at the right time.
		  ;;
		  ;; Once again, return nil to stay in the loop.
		  ((not (member fn-lbl seen-refs))
		   (push fn-lbl seen-refs)
		   (funcall search-ref
			    (org-export-get-footnote-definition fn info))
		   nil))))
	     info 'first-match)))))
    (catch 'exit (funcall search-ref (plist-get info :parse-tree)))))


;;;; For Headlines

;; `org-export-get-relative-level' is a shortcut to get headline
;; level, relatively to the lower headline level in the parsed tree.

;; `org-export-get-headline-number' returns the section number of an
;; headline, while `org-export-number-to-roman' allows to convert it
;; to roman numbers.

;; `org-export-low-level-p', `org-export-first-sibling-p' and
;; `org-export-last-sibling-p' are three useful predicates when it
;; comes to fulfill the `:headline-levels' property.

(defun org-export-get-relative-level (headline info)
  "Return HEADLINE relative level within current parsed tree.
INFO is a plist holding contextual information."
  (+ (org-element-property :level headline)
     (or (plist-get info :headline-offset) 0)))

(defun org-export-low-level-p (headline info)
  "Non-nil when HEADLINE is considered as low level.

INFO is a plist used as a communication channel.

A low level headlines has a relative level greater than
`:headline-levels' property value.

Return value is the difference between HEADLINE relative level
and the last level being considered as high enough, or nil."
  (let ((limit (plist-get info :headline-levels)))
    (when (wholenump limit)
      (let ((level (org-export-get-relative-level headline info)))
        (and (> level limit) (- level limit))))))

(defun org-export-get-headline-number (headline info)
  "Return HEADLINE numbering as a list of numbers.
INFO is a plist holding contextual information."
  (cdr (assoc headline (plist-get info :headline-numbering))))

(defun org-export-number-to-roman (n)
  "Convert integer N into a roman numeral."
  (let ((roman '((1000 . "M") (900 . "CM") (500 . "D") (400 . "CD")
		 ( 100 . "C") ( 90 . "XC") ( 50 . "L") ( 40 . "XL")
		 (  10 . "X") (  9 . "IX") (  5 . "V") (  4 . "IV")
		 (   1 . "I")))
	(res ""))
    (if (<= n 0)
	(number-to-string n)
      (while roman
	(if (>= n (caar roman))
	    (setq n (- n (caar roman))
		  res (concat res (cdar roman)))
	  (pop roman)))
      res)))

(defun org-export-first-sibling-p (headline info)
  "Non-nil when HEADLINE is the first sibling in its sub-tree.
INFO is the plist used as a communication channel."
  (not (eq (org-element-type (org-export-get-previous-element headline info))
	   'headline)))

(defun org-export-last-sibling-p (headline info)
  "Non-nil when HEADLINE is the last sibling in its sub-tree.
INFO is the plist used as a communication channel."
  (not (org-export-get-next-element headline info)))


;;;; For Links

;; `org-export-solidify-link-text' turns a string into a safer version
;; for links, replacing most non-standard characters with hyphens.

;; `org-export-get-coderef-format' returns an appropriate format
;; string for coderefs.

;; `org-export-inline-image-p' returns a non-nil value when the link
;; provided should be considered as an inline image.

;; `org-export-resolve-fuzzy-link' searches destination of fuzzy links
;; (i.e. links with "fuzzy" as type) within the parsed tree, and
;; returns an appropriate unique identifier when found, or nil.

;; `org-export-resolve-id-link' returns the first headline with
;; specified id or custom-id in parse tree, or nil when none was
;; found.

;; `org-export-resolve-coderef' associates a reference to a line
;; number in the element it belongs, or returns the reference itself
;; when the element isn't numbered.

(defun org-export-solidify-link-text (s)
  "Take link text S and make a safe target out of it."
  (save-match-data
    (mapconcat 'identity (org-split-string s "[^a-zA-Z0-9_.-]+") "-")))

(defun org-export-get-coderef-format (path desc)
  "Return format string for code reference link.
PATH is the link path.  DESC is its description."
  (save-match-data
    (cond ((string-match (regexp-quote (concat "(" path ")")) desc)
	   (replace-match "%s" t t desc))
	  ((string= desc "") "%s")
	  (t desc))))

(defun org-export-inline-image-p (link &optional rules)
  "Non-nil if LINK object points to an inline image.

Optional argument is a set of RULES defining inline images.  It
is an alist where associations have the following shape:

  \(TYPE . REGEXP)

Applying a rule means apply REGEXP against LINK's path when its
type is TYPE.  The function will return a non-nil value if any of
the provided rules is non-nil.  The default rule is
`org-export-default-inline-image-rule'.

This only applies to links without a description."
  (and (not (org-element-contents link))
       (let ((case-fold-search t)
	     (rules (or rules org-export-default-inline-image-rule)))
	 (some
	  (lambda (rule)
	    (and (string= (org-element-property :type link) (car rule))
		 (string-match (cdr rule)
			       (org-element-property :path link))))
	  rules))))

(defun org-export-resolve-fuzzy-link (link info)
  "Return LINK destination.

INFO is a plist holding contextual information.

Return value can be an object, an element, or nil:

- If LINK path matches a target object (i.e. <<path>>) or
  element (i.e. \"#+target: path\"), return it.

- If LINK path exactly matches the name affiliated keyword
  \(i.e. #+name: path) of an element, return that element.

- If LINK path exactly matches any headline name, return that
  element.  If more than one headline share that name, priority
  will be given to the one with the closest common ancestor, if
  any, or the first one in the parse tree otherwise.

- Otherwise, return nil.

Assume LINK type is \"fuzzy\"."
  (let ((path (org-element-property :path link)))
    (cond
     ;; First try to find a matching "<<path>>" unless user specified
     ;; he was looking for an headline (path starts with a *
     ;; character).
     ((and (not (eq (substring path 0 1) ?*))
	   (loop for target in (plist-get info :target-list)
		 when (string= (org-element-property :value target) path)
		 return target)))
     ;; Then try to find an element with a matching "#+name: path"
     ;; affiliated keyword.
     ((and (not (eq (substring path 0 1) ?*))
	   (org-element-map
	    (plist-get info :parse-tree) org-element-all-elements
	    (lambda (el)
              (when (string= (org-element-property :name el) path) el))
	    info 'first-match)))
     ;; Last case: link either points to an headline or to
     ;; nothingness.  Try to find the source, with priority given to
     ;; headlines with the closest common ancestor.  If such candidate
     ;; is found, return its beginning position as an unique
     ;; identifier, otherwise return nil.
     (t
      (let ((find-headline
	       (function
		;; Return first headline whose `:raw-value' property
		;; is NAME in parse tree DATA, or nil.
		(lambda (name data)
		  (org-element-map
		   data 'headline
		   (lambda (headline)
		     (when (string=
			    (org-element-property :raw-value headline)
			    name)
		       headline))
		   info 'first-match)))))
	  ;; Search among headlines sharing an ancestor with link,
	  ;; from closest to farthest.
	  (or (catch 'exit
		(mapc
		 (lambda (parent)
		   (when (eq (org-element-type parent) 'headline)
		     (let ((foundp (funcall find-headline path parent)))
		       (when foundp (throw 'exit foundp)))))
		 (org-export-get-genealogy link info)) nil)
	      ;; No match with a common ancestor: try the full parse-tree.
	      (funcall find-headline path (plist-get info :parse-tree))))))))

(defun org-export-resolve-id-link (link info)
  "Return headline referenced as LINK destination.

INFO is a plist used as a communication channel.

Return value can be an headline element or nil.  Assume LINK type
is either \"id\" or \"custom-id\"."
  (let ((id (org-element-property :path link)))
    (org-element-map
     (plist-get info :parse-tree) 'headline
     (lambda (headline)
       (when (or (string= (org-element-property :id headline) id)
                 (string= (org-element-property :custom-id headline) id))
         headline))
     info 'first-match)))

(defun org-export-resolve-coderef (ref info)
  "Resolve a code reference REF.

INFO is a plist used as a communication channel.

Return associated line number in source code, or REF itself,
depending on src-block or example element's switches."
  (org-element-map
   (plist-get info :parse-tree) '(src-block example)
   (lambda (el)
     (let ((switches (or (org-element-property :switches el) "")))
       (with-temp-buffer
         (insert (org-trim (org-element-property :value el)))
         ;; Build reference regexp.
         (let* ((label
                 (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
                          (match-string 1 switches))
                     org-coderef-label-format))
                (ref-re
                 (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
                         (replace-regexp-in-string "%s" ref label nil t))))
           ;; Element containing REF is found.  Only associate REF to
           ;; a line number if element has "+n" or "-n" and "-k" or
           ;; "-r" as switches.  When it has "+n", count accumulated
           ;; locs before, too.
           (when (re-search-backward ref-re nil t)
             (cond
              ((not (string-match "-[kr]\\>" switches)) ref)
              ((string-match "-n\\>" switches) (line-number-at-pos))
	      ((string-match "\\+n\\>" switches)
	       (+ (org-export-get-loc el info) (line-number-at-pos)))
              (t ref)))))))
   info 'first-match))


;;;; For Macros

;; `org-export-expand-macro' simply takes care of expanding macros.

(defun org-export-expand-macro (macro info)
  "Expand MACRO and return it as a string.
INFO is a plist holding export options."
  (let* ((key (org-element-property :key macro))
	 (args (org-element-property :args macro))
	 ;; User's macros are stored in the communication channel with
	 ;; a ":macro-" prefix.  If it's a string leave it as-is.
	 ;; Otherwise, it's a secondary string that needs to be
	 ;; expanded recursively.
	 (value
	  (let ((val (plist-get info (intern (format ":macro-%s" key)))))
	    (if (stringp val) val
	      (org-export-secondary-string
	       val (plist-get info :back-end) info)))))
    ;; Replace arguments in VALUE.
    (let ((s 0) n)
      (while (string-match "\\$\\([0-9]+\\)" value s)
	(setq s (1+ (match-beginning 0))
	      n (string-to-number (match-string 1 value)))
	(and (>= (length args) n)
	     (setq value (replace-match (nth (1- n) args) t t value)))))
    ;; VALUE starts with "(eval": it is a s-exp, `eval' it.
    (when (string-match "\\`(eval\\>" value)
      (setq value (eval (read value))))
    ;; Return string.
    (format "%s" (or value ""))))


;;;; For References

;; `org-export-get-ordinal' associates a sequence number to any object
;; or element.

(defun org-export-get-ordinal
  (element info &optional types within-section predicate)
  "Return ordinal number of an element or object.

ELEMENT is the element or object considered.  INFO is the plist
used as a communication channel.

Optional argument TYPES, when non-nil, is a list of element or
object types, as symbols, that should also be counted in.
Otherwise, only provided element's type is considered.

When optional argument WITHIN-SECTION is non-nil, narrow counting
to the section containing ELEMENT.

Optional argument PREDICATE is a function returning a non-nil
value if the current element or object should be counted in.  It
accepts one argument: the element or object being considered.
This argument allows to count only a certain type of objects,
like inline images, which are a subset of links (in that case,
`org-export-inline-image-p' might be an useful predicate).

Return value is a list of numbers if ELEMENT is an headline or an
item.  It is nil for keywords.  It represents the footnote number
for footnote definitions and footnote references.  If ELEMENT is
a target, return the same value as if ELEMENT was the closest
table, item or headline containing the target.  In any other
case, return the sequence number of ELEMENT among elements or
objects of the same type."
  ;; A target keyword, representing an invisible target, never has
  ;; a sequence number.
  (unless (eq (org-element-type element) 'keyword)
    ;; Ordinal of a target object refer to the ordinal of the closest
    ;; table, item, or headline containing the object.
    (when (eq (org-element-type element) 'target)
      (setq element
	    (loop for parent in (org-export-get-genealogy element info)
		  when
		  (memq
		   (org-element-type parent)
		   '(footnote-definition footnote-reference headline item
                                         table))
		  return parent)))
    (case (org-element-type element)
      ;; Special case 1: An headline returns its number as a list.
      (headline (org-export-get-headline-number element info))
      ;; Special case 2: An item returns its number as a list.
      (item (let ((struct (org-element-property :structure element)))
	      (org-list-get-item-number
	       (org-element-property :begin element)
	       struct
	       (org-list-prevs-alist struct)
	       (org-list-parents-alist struct))))
      ((footnote definition footnote-reference)
       (org-export-get-footnote-number element info))
      (otherwise
       (let ((counter 0)
	     ;; Determine if search should apply to current section,
	     ;; in which case it should be retrieved first, or to full
	     ;; parse tree.  As a special case, an element or object
	     ;; without a parent headline will also trigger a full
	     ;; search, notwithstanding WITHIN-SECTION value.
	     (data
	      (if (not within-section) (plist-get info :parse-tree)
		(or (org-export-get-parent-headline element info)
		    (plist-get info :parse-tree)))))
	 ;; Increment counter until ELEMENT is found again.
	 (org-element-map
	  data (or types (org-element-type element))
	  (lambda (el)
	    (cond
	     ((equal element el) (1+ counter))
	     ((not predicate) (incf counter) nil)
	     ((funcall predicate el) (incf counter) nil)))
	  info 'first-match))))))


;;;; For Src-Blocks

;; `org-export-get-loc' counts number of code lines accumulated in
;; src-block or example-block elements with a "+n" switch until
;; a given element, excluded.  Note: "-n" switches reset that count.

;; `org-export-handle-code' takes care of line numbering and reference
;; cleaning in source code, when appropriate.

(defun org-export-get-loc (element info)
  "Return accumulated lines of code up to ELEMENT.

INFO is the plist used as a communication channel.

ELEMENT is excluded from count."
  (let ((loc 0))
    (org-element-map
     (plist-get info :parse-tree)
     `(src-block example-block ,(org-element-type element))
     (lambda (el)
       (cond
        ;; ELEMENT is reached: Quit the loop.
        ((equal el element) t)
        ;; Only count lines from src-block and example-block elements
        ;; with a "+n" or "-n" switch.  A "-n" switch resets counter.
        ((not (memq (org-element-type el) '(src-block example-block))) nil)
        ((let ((switches (org-element-property :switches el)))
           (when (and switches (string-match "\\([-+]\\)n\\>" switches))
	     ;; Accumulate locs or reset them.
	     (let ((accumulatep (string= (match-string 1 switches) "-"))
		   (lines (org-count-lines
			   (org-trim (org-element-property :value el)))))
	       (setq loc (if accumulatep lines (+ loc lines))))))
	 ;; Return nil to stay in the loop.
         nil)))
     info 'first-match)
    ;; Return value.
    loc))

(defun org-export-handle-code (element info &optional num-fmt ref-fmt delayed)
  "Handle line numbers and code references in ELEMENT.

ELEMENT has either a `src-block' an `example-block' type.  INFO
is a plist used as a communication channel.

If optional argument NUM-FMT is a string, it will be used as
a format string for numbers at beginning of each line.

If optional argument REF-FMT is a string, it will be used as
a format string for each line of code containing a reference.

When optional argument DELAYED is non-nil, `org-loc' and
`org-coderef' properties, set to an adequate value, are applied
to, respectively, numbered lines and lines with a reference.  No
line numbering is done and all references are stripped from the
resulting string.  Both NUM-FMT and REF-FMT arguments are ignored
in that situation.

Return new code as a string."
  (let* ((switches (or (org-element-property :switches element) ""))
	 (code (org-element-property :value element))
	 (numberp (string-match "[-+]n\\>" switches))
	 (accumulatep (string-match "\\+n\\>" switches))
	 ;; Initialize loc counter when any kind of numbering is
	 ;; active.
	 (total-LOC (cond
		     (accumulatep (org-export-get-loc element info))
		     (numberp 0)))
	 ;; Get code and clean it.  Remove blank lines at its
	 ;; beginning and end.  Also remove protective commas.
	 (preserve-indent-p (or org-src-preserve-indentation
				(string-match "-i\\>" switches)))
	 (replace-labels (when (string-match "-r\\>" switches)
			   (if (string-match "-k\\>" switches) 'keep t)))
	 (code (let ((c (replace-regexp-in-string
			 "\\`\\([ \t]*\n\\)+" ""
			 (replace-regexp-in-string
			  "\\(:?[ \t]*\n\\)*[ \t]*\\'" "\n" code))))
		 ;; If appropriate, remove global indentation.
		 (unless preserve-indent-p (setq c (org-remove-indentation c)))
		 ;; Free up the protected lines.  Note: Org blocks
		 ;; have commas at the beginning or every line.
		 (if (string=
		      (or (org-element-property :language element) "")
		      "org")
		     (replace-regexp-in-string "^," "" c)
		   (replace-regexp-in-string
		    "^\\(,\\)\\(:?\\*\\|[ \t]*#\\+\\)" "" c nil nil 1))))
	 ;; Split code to process it line by line.
	 (code-lines (org-split-string code "\n"))
	 ;; If numbering is active, ensure line numbers will be
	 ;; correctly padded before applying the format string.
	 (num-fmt
	  (when (and (not delayed) numberp)
	    (format (if (stringp num-fmt) num-fmt "%s:  ")
		    (format "%%%ds"
			    (length (number-to-string
				     (+ (length code-lines) total-LOC)))))))
	 ;; Get format used for references.
	 (label-fmt (or (and (string-match "-l +\"\\([^\"\n]+\\)\"" switches)
			     (match-string 1 switches))
			org-coderef-label-format))
	 ;; Build a regexp matching a loc with a reference.
	 (with-ref-re (format "^.*?\\S-.*?\\([ \t]*\\(%s\\)\\)[ \t]*$"
			      (replace-regexp-in-string
			       "%s" "\\([-a-zA-Z0-9_ ]+\\)" label-fmt nil t))))
    (org-element-normalize-string
     (mapconcat
      (lambda (loc)
	;; Maybe add line number to current line of code (LOC).
	(when numberp
	  (incf total-LOC)
	  (setq loc (if delayed (org-add-props loc nil 'org-loc total-LOC)
		      (concat (format num-fmt total-LOC) loc))))
	;; Take action if at a ref line.
	(when (string-match with-ref-re loc)
	  (let ((ref (match-string 3 loc)))
	    (setq loc
		  ;; Option "-r" without "-k" removes labels.
		  ;; A non-nil DELAYED removes labels unconditionally.
		  (if (or delayed
			  (and replace-labels (not (eq replace-labels 'keep))))
		      (replace-match "" nil nil loc 1)
		    (replace-match (format "(%s)" ref) nil nil loc 2)))
	    ;; Store REF in `org-coderef' property if DELAYED asks to.
	    (cond (delayed (setq loc (org-add-props loc nil 'org-coderef ref)))
		  ;; If REF-FMT is defined, apply it to current LOC.
		  ((stringp ref-fmt) (setq loc (format ref-fmt loc))))))
	;; Return updated LOC for concatenation.
	loc)
      code-lines "\n"))))


;;;; For Tables

;; `org-export-table-format-info' extracts formatting information
;; (alignment, column groups and presence of a special column) from
;; a raw table and returns it as a property list.
;;
;; `org-export-clean-table' cleans the raw table from any Org
;; table-specific syntax.

(defun org-export-table-format-info (table)
  "Extract info from TABLE.
Return a plist whose properties and values are:
`:alignment'        vector of strings among \"r\", \"l\" and \"c\",
`:column-groups'    vector of symbols among `start', `end', `start-end',
`:row-groups'       list of integers representing row groups.
`:special-column-p' non-nil if table has a special column.
`:width'            vector of integers representing desired width of
		    current column, or nil."
  (with-temp-buffer
    (insert table)
    (goto-char 1)
    (org-table-align)
    (let ((align (vconcat (mapcar (lambda (c) (if c "r" "l"))
				  org-table-last-alignment)))
	  (width (make-vector (length org-table-last-alignment) nil))
	  (colgroups (make-vector (length org-table-last-alignment) nil))
	  (row-group 0)
	  (rowgroups)
	  (special-column-p 'empty))
      (mapc (lambda (row)
	      (if (string-match "^[ \t]*|[-+]+|[ \t]*$" row)
		  (incf row-group)
		;; Determine if a special column is present by looking
		;; for special markers in the first column.  More
		;; accurately, the first column is considered special
		;; if it only contains special markers and, maybe,
		;; empty cells.
		(setq special-column-p
		      (cond
		       ((not special-column-p) nil)
		       ((string-match "^[ \t]*| *\\\\?\\([/#!$*_^]\\) *|" row)
			'special)
		       ((string-match "^[ \t]*| +|" row) special-column-p))))
	      (cond
	       ;; Read forced alignment and width information, if any,
	       ;; and determine final alignment for the table.
	       ((org-table-cookie-line-p row)
		(let ((col 0))
		  (mapc (lambda (field)
			  (when (string-match
				 "<\\([lrc]\\)?\\([0-9]+\\)?>" field)
			    (let ((align-data (match-string 1 field)))
			      (when align-data (aset align col align-data)))
			    (let ((w-data (match-string 2 field)))
			      (when w-data
				(aset width col (string-to-number w-data)))))
			  (incf col))
			(org-split-string row "[ \t]*|[ \t]*"))))
	       ;; Read column groups information.
	       ((org-table-colgroup-line-p row)
		(let ((col 0))
		  (mapc (lambda (field)
			  (aset colgroups col
				(cond ((string= "<" field) 'start)
				      ((string= ">" field) 'end)
				      ((string= "<>" field) 'start-end)))
			  (incf col))
			(org-split-string row "[ \t]*|[ \t]*"))))
	       ;; Contents line.
	       (t (push row-group rowgroups))))
	    (org-split-string table "\n"))
      ;; Return plist.
      (list :alignment align
	    :column-groups colgroups
	    :row-groups (reverse rowgroups)
	    :special-column-p (eq special-column-p 'special)
	    :width width))))

(defun org-export-clean-table (table specialp)
  "Clean string TABLE from its formatting elements.
Remove any row containing column groups or formatting cookies and
rows starting with a special marker.  If SPECIALP is non-nil,
assume the table contains a special formatting column and remove
it also."
  (let ((rows (org-split-string table "\n")))
    (mapconcat 'identity
	       (delq nil
		     (mapcar
		      (lambda (row)
			(cond
			 ((org-table-colgroup-line-p row) nil)
			 ((org-table-cookie-line-p row) nil)
			 ;; Ignore rows starting with a special marker.
			 ((string-match "^[ \t]*| *[!_^/$] *|" row) nil)
			 ;; Remove special column.
			 ((and specialp
			       (or (string-match "^\\([ \t]*\\)|-+\\+" row)
				   (string-match "^\\([ \t]*\\)|[^|]*|" row)))
			  (replace-match "\\1|" t nil row))
			 (t row)))
		      rows))
	       "\n")))


;;;; For Tables Of Contents

;; `org-export-collect-headlines' builds a list of all exportable
;; headline elements, maybe limited to a certain depth.  One can then
;; easily parse it and transcode it.

;; Building lists of tables, figures or listings is quite similar.
;; Once the generic function `org-export-collect-elements' is defined,
;; `org-export-collect-tables', `org-export-collect-figures' and
;; `org-export-collect-listings' can be derived from it.

(defun org-export-collect-headlines (info &optional n)
  "Collect headlines in order to build a table of contents.

INFO is a plist used as a communication channel.

When non-nil, optional argument N must be an integer.  It
specifies the depth of the table of contents.

Return a list of all exportable headlines as parsed elements."
  (org-element-map
   (plist-get info :parse-tree)
   'headline
   (lambda (headline)
     ;; Strip contents from HEADLINE.
     (let ((relative-level (org-export-get-relative-level headline info)))
       (unless (and n (> relative-level n)) headline)))
   info))

(defun org-export-collect-elements (type info &optional predicate)
  "Collect referenceable elements of a determined type.

TYPE can be a symbol or a list of symbols specifying element
types to search.  Only elements with a caption or a name are
collected.

INFO is a plist used as a communication channel.

When non-nil, optional argument PREDICATE is a function accepting
one argument, an element of type TYPE.  It returns a non-nil
value when that element should be collected.

Return a list of all elements found, in order of appearance."
  (org-element-map
   (plist-get info :parse-tree) type
   (lambda (element)
     (and (or (org-element-property :caption element)
	      (org-element-property :name element))
	  (or (not predicate) (funcall predicate element))
	  element)) info))

(defun org-export-collect-tables (info)
  "Build a list of tables.

INFO is a plist used as a communication channel.

Return a list of table elements with a caption or a name
affiliated keyword."
  (org-export-collect-elements 'table info))

(defun org-export-collect-figures (info predicate)
  "Build a list of figures.

INFO is a plist used as a communication channel.  PREDICATE is
a function which accepts one argument: a paragraph element and
whose return value is non-nil when that element should be
collected.

A figure is a paragraph type element, with a caption or a name,
verifying PREDICATE.  The latter has to be provided since
a \"figure\" is a vague concept that may depend on back-end.

Return a list of elements recognized as figures."
  (org-export-collect-elements 'paragraph info predicate))

(defun org-export-collect-listings (info)
  "Build a list of src blocks.

INFO is a plist used as a communication channel.

Return a list of src-block elements with a caption or a name
affiliated keyword."
  (org-export-collect-elements 'src-block info))


;;;; Topology

;; Here are various functions to retrieve information about the
;; neighbourhood of a given element or object.  Neighbours of interest
;; are direct parent (`org-export-get-parent'), parent headline
;; (`org-export-get-parent-headline'), parent paragraph
;; (`org-export-get-parent-paragraph'), previous element or object
;; (`org-export-get-previous-element') and next element or object
;; (`org-export-get-next-element').

;; All of these functions are just a specific use of the more generic
;; `org-export-get-genealogy', which returns the genealogy relative to
;; the element or object.

(defun org-export-get-genealogy (blob info)
  "Return genealogy relative to a given element or object.
BLOB is the element or object being considered.  INFO is a plist
used as a communication channel."
  (let* ((type (org-element-type blob))
	 (end (org-element-property :end blob))
         (walk-data
          (lambda (data genealogy)
	    ;; Walk DATA, looking for BLOB.  GENEALOGY is the list of
	    ;; parents of all elements in DATA.
            (mapc
             (lambda (el)
               (cond
		((stringp el) nil)
                ((equal el blob) (throw 'exit genealogy))
                ((>= (org-element-property :end el) end)
		 ;; If BLOB is an object and EL contains a secondary
		 ;; string, be sure to check it.
		 (when (memq type org-element-all-objects)
		   (let ((sec-prop
			  (cdr (assq (org-element-type el)
				     org-element-secondary-value-alist))))
		     (when sec-prop
		       (funcall
			walk-data
			(cons 'org-data
			      (cons nil (org-element-property sec-prop el)))
			(cons el genealogy)))))
                 (funcall walk-data el (cons el genealogy)))))
	     (org-element-contents data)))))
    (catch 'exit (funcall walk-data (plist-get info :parse-tree) nil) nil)))

(defun org-export-get-parent (blob info)
  "Return BLOB parent or nil.
BLOB is the element or object considered.  INFO is a plist used
as a communication channel."
  (car (org-export-get-genealogy blob info)))

(defun org-export-get-parent-headline (blob info)
  "Return closest parent headline or nil.

BLOB is the element or object being considered.  INFO is a plist
used as a communication channel."
  (catch 'exit
    (mapc
     (lambda (el) (when (eq (org-element-type el) 'headline) (throw 'exit el)))
     (org-export-get-genealogy blob info))
    nil))

(defun org-export-get-parent-paragraph (object info)
  "Return parent paragraph or nil.

INFO is a plist used as a communication channel.

Optional argument OBJECT, when provided, is the object to consider.
Otherwise, return the paragraph containing current object.

This is useful for objects, which share attributes with the
paragraph containing them."
  (catch 'exit
    (mapc
     (lambda (el) (when (eq (org-element-type el) 'paragraph) (throw 'exit el)))
     (org-export-get-genealogy object info))
    nil))

(defun org-export-get-previous-element (blob info)
  "Return previous element or object.

BLOB is an element or object.  INFO is a plist used as
a communication channel.

Return previous element or object, a string, or nil."
  (let ((parent (org-export-get-parent blob info)))
    (cadr (member blob (reverse (org-element-contents parent))))))

(defun org-export-get-next-element (blob info)
  "Return next element or object.

BLOB is an element or object.  INFO is a plist used as
a communication channel.

Return next element or object, a string, or nil."
  (let ((parent (org-export-get-parent blob info)))
    (cadr (member blob (org-element-contents parent)))))


\f
;;; The Dispatcher

;; `org-export-dispatch' is the standard interactive way to start an
;; export process.  It uses `org-export-dispatch-ui' as a subroutine
;; for its interface.  Most commons back-ends should have an entry in
;; it.

(defun org-export-dispatch ()
  "Export dispatcher for Org mode.

It provides an access to common export related tasks in a buffer.
Its interface comes in two flavours: standard and expert.  While
both share the same set of bindings, only the former displays the
valid keys associations.  Set `org-export-dispatch-use-expert-ui'
to switch to one or the other.

Return an error if key pressed has no associated command."
  (interactive)
  (let* ((input (org-export-dispatch-ui
		 (if (listp org-export-initial-scope) org-export-initial-scope
		   (list org-export-initial-scope))
		 org-export-dispatch-use-expert-ui))
	 (raw-key (car input))
	 (optns (cdr input)))
    ;; Translate "C-a", "C-b"... into "a", "b"... Then take action
    ;; depending on user's key pressed.
    (case (if (< raw-key 27) (+ raw-key 96) raw-key)
      ;; Allow to quit with "q" key.
      (?q nil)
      ;; Export with `e-ascii' back-end.
      ((?A ?N ?U)
       (let ((outbuf
	      (org-export-to-buffer
	       'e-ascii "*Org E-ASCII Export*"
	       (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
	       `(:ascii-charset
		 ,(case raw-key (?A 'ascii) (?N 'latin1) (t 'utf-8))))))
	 (with-current-buffer outbuf (text-mode))
	 (when org-export-show-temporary-export-buffer
	   (switch-to-buffer-other-window outbuf))))
      ((?a ?n ?u)
       (org-e-ascii-export-to-ascii
	(memq 'subtree optns) (memq 'visible optns) (memq 'body optns)
	`(:ascii-charset ,(case raw-key (?a 'ascii) (?n 'latin1) (t 'utf-8)))))
      ;; Export with `e-latex' back-end.
      (?L
       (let ((outbuf
	      (org-export-to-buffer
	       'e-latex "*Org E-LaTeX Export*"
	       (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
	 (with-current-buffer outbuf (latex-mode))
	 (when org-export-show-temporary-export-buffer
	   (switch-to-buffer-other-window outbuf))))
      (?l (org-e-latex-export-to-latex
	   (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
      (?p (org-e-latex-export-to-pdf
	   (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
      (?d (org-open-file
	   (org-e-latex-export-to-pdf
	    (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
      ;; Export with `e-html' back-end.
      (?H
       (let ((outbuf
	      (org-export-to-buffer
	       'e-html "*Org E-HTML Export*"
	       (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
	 ;; set major mode
	 (with-current-buffer outbuf
	   (if (featurep 'nxhtml-mode) (nxhtml-mode) (nxml-mode)))
	 (when org-export-show-temporary-export-buffer
	   (switch-to-buffer-other-window outbuf))))
      (?h (org-e-html-export-to-html
	   (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
      (?b (org-open-file
	   (org-e-html-export-to-html
	    (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
      ;; Export with `e-odt' back-end.
      (?o (org-e-odt-export-to-odt
	   (memq 'subtree optns) (memq 'visible optns) (memq 'body optns)))
      (?O (org-open-file
	   (org-e-odt-export-to-odt
	    (memq 'subtree optns) (memq 'visible optns) (memq 'body optns))))
      ;; Publishing facilities
      (?F (org-e-publish-current-file (memq 'force optns)))
      (?P (org-e-publish-current-project (memq 'force optns)))
      (?X (let ((project
		 (assoc (org-icompleting-read
			 "Publish project: " org-e-publish-project-alist nil t)
			org-e-publish-project-alist)))
	    (org-e-publish project (memq 'force optns))))
      (?E (org-e-publish-all (memq 'force optns)))
      ;; Undefined command.
      (t (error "No command associated with key %s"
		(char-to-string raw-key))))))

(defun org-export-dispatch-ui (options expertp)
  "Handle interface for `org-export-dispatch'.

OPTIONS is a list containing current interactive options set for
export.  It can contain any of the following symbols:
`body'    toggles a body-only export
`subtree' restricts export to current subtree
`visible' restricts export to visible part of buffer.
`force'   force publishing files.

EXPERTP, when non-nil, triggers expert UI.  In that case, no help
buffer is provided, but indications about currently active
options are given in the prompt.  Moreover, \[?] allows to switch
back to standard interface.

Return value is a list with key pressed as CAR and a list of
final interactive export options as CDR."
  (let ((help
	 (format "---- (Options) -------------------------------------------

\[1] Body only:     %s       [2] Export scope:     %s
\[3] Visible only:  %s       [4] Force publishing: %s


--- (ASCII/Latin-1/UTF-8 Export) -------------------------

\[a/n/u] to TXT file          [A/N/U] to temporary buffer

--- (HTML Export) ----------------------------------------

\[h] to HTML file             [b] ... and open it
\[H] to temporary buffer

--- (LaTeX Export) ---------------------------------------

\[l] to TEX file              [L] to temporary buffer
\[p] to PDF file              [d] ... and open it

--- (ODF Export) -----------------------------------------

\[o] to ODT file              [O] ... and open it

--- (Publish) --------------------------------------------

\[F] current file             [P] current project
\[X] a project                [E] every project"
		 (if (memq 'body options) "On " "Off")
		 (if (memq 'subtree options) "Subtree" "Buffer ")
		 (if (memq 'visible options) "On " "Off")
		 (if (memq 'force options) "On " "Off")))
	(standard-prompt "Export command: ")
	(expert-prompt (format "Export command (%s%s%s%s): "
			       (if (memq 'body options) "b" "-")
			       (if (memq 'subtree options) "s" "-")
			       (if (memq 'visible options) "v" "-")
			       (if (memq 'force options) "f" "-")))
	(handle-keypress
	 (function
	  ;; Read a character from command input, toggling interactive
	  ;; options when applicable.  PROMPT is the displayed prompt,
	  ;; as a string.
	  (lambda (prompt)
	    (let ((key (read-char-exclusive prompt)))
	      (cond
	       ;; Ignore non-standard characters (i.e. "M-a").
	       ((not (characterp key)) (org-export-dispatch-ui options expertp))
	       ;; Help key: Switch back to standard interface if
	       ;; expert UI was active.
	       ((eq key ??) (org-export-dispatch-ui options nil))
	       ;; Toggle export options.
	       ((memq key '(?1 ?2 ?3 ?4))
		(org-export-dispatch-ui
		 (let ((option (case key (?1 'body) (?2 'subtree) (?3 'visible)
				     (?4 'force))))
		   (if (memq option options) (remq option options)
		     (cons option options)))
		 expertp))
	       ;; Action selected: Send key and options back to
	       ;; `org-export-dispatch'.
	       (t (cons key options))))))))
    ;; With expert UI, just read key with a fancy prompt.  In standard
    ;; UI, display an intrusive help buffer.
    (if expertp (funcall handle-keypress expert-prompt)
      (save-window-excursion
	(delete-other-windows)
	(with-output-to-temp-buffer "*Org Export/Publishing Help*" (princ help))
	(org-fit-window-to-buffer
	 (get-buffer-window "*Org Export/Publishing Help*"))
	(funcall handle-keypress standard-prompt)))))


(provide 'org-export)
;;; org-export.el ends here

debug log:

solving e7cca50 ...
found e7cca50 in https://yhetil.org/emacs/87399wrrqx.fsf@gmail.com/
found b809758 in https://git.savannah.gnu.org/cgit/emacs.git
preparing index
index prepared:
100644 b8097584e153a6ec540df1ddd0713e7068f1309d	contrib/lisp/org-export.el

applying [1/1] https://yhetil.org/emacs/87399wrrqx.fsf@gmail.com/
diff --git a/contrib/lisp/org-export.el b/contrib/lisp/org-export.el
index b809758..e7cca50 100644

Checking patch contrib/lisp/org-export.el...
Applied patch contrib/lisp/org-export.el cleanly.

index at:
100644 e7cca509b19d705902a1be7187b996b4f82727c9	contrib/lisp/org-export.el

(*) Git path names are given by the tree(s) the blob belongs to.
    Blobs themselves have no identifier aside from the hash of its contents.^

Code repositories for project(s) associated with this external index

	https://git.savannah.gnu.org/cgit/emacs.git
	https://git.savannah.gnu.org/cgit/emacs/org-mode.git

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.