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
# .. coding: utf-8
# $Id: __init__.py 8676 2021-04-08 16:36:09Z milde $
# Author: Engelbert Gruber, Günter Milde
# Maintainer: docutils-develop@lists.sourceforge.net
# Copyright: This module has been placed in the public domain.

"""LaTeX2e document tree Writer."""

__docformat__ = 'reStructuredText'

# code contributions from several people included, thanks to all.
# some named: David Abrahams, Julien Letessier, Lele Gaifax, and others.
#
# convention deactivate code by two # i.e. ##.

import os
import re
import string
import sys

if sys.version_info < (3, 0):
    from io import open
    from urllib import url2pathname
else:
    from urllib.request import url2pathname

try:
    import roman
except ImportError:
    import docutils.utils.roman as roman

import docutils
from docutils import frontend, nodes, languages, writers, utils
from docutils.utils.error_reporting import SafeString
from docutils.transforms import writer_aux
from docutils.utils.math import pick_math_environment, unichar2tex

if sys.version_info >= (3, 0):
    unicode = str  # noqa


class Writer(writers.Writer):

    supported = ('latex', 'latex2e')
    """Formats this writer supports."""

    default_template = 'default.tex'
    default_template_path = os.path.dirname(os.path.abspath(__file__))
    default_preamble = '\n'.join([r'% PDF Standard Fonts',
                                  r'\usepackage{mathptmx} % Times',
                                  r'\usepackage[scaled=.90]{helvet}',
                                  r'\usepackage{courier}'])
    table_style_values = ('standard', 'booktabs', 'nolines', 'borderless',
                          'colwidths-auto', 'colwidths-given')

    settings_spec = (
        'LaTeX-Specific Options',
        None,
        (('Specify LaTeX documentclass.  Default: "article".',
          ['--documentclass'],
          {'default': 'article', }),
         ('Specify document options.  Multiple options can be given, '
          'separated by commas.  Default: "a4paper".',
          ['--documentoptions'],
          {'default': 'a4paper', }),
         ('Format for footnote references: one of "superscript" or '
          '"brackets".  Default: "superscript".',
          ['--footnote-references'],
          {'choices': ['superscript', 'brackets'], 'default': 'superscript',
           'metavar': '<format>',
           'overrides': 'trim_footnote_reference_space'}),
         ('Use \\cite command for citations. (future default)',
          ['--use-latex-citations'],
          {'default': False, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Use figure floats for citations '
          '(might get mixed with real figures). (current default)',
          ['--figure-citations'],
          {'dest': 'use_latex_citations', 'action': 'store_false',
           'validator': frontend.validate_boolean}),
         ('Format for block quote attributions: one of "dash" (em-dash '
          'prefix), "parentheses"/"parens", or "none".  Default: "dash".',
          ['--attribution'],
          {'choices': ['dash', 'parentheses', 'parens', 'none'],
           'default': 'dash', 'metavar': '<format>'}),
         ('Specify LaTeX packages/stylesheets. '
          'A style is referenced with "\\usepackage" if extension is '
          '".sty" or omitted and with "\\input" else. '
          ' Overrides previous --stylesheet and --stylesheet-path settings.',
          ['--stylesheet'],
          {'default': '', 'metavar': '<file[,file,...]>',
           'overrides': 'stylesheet_path',
           'validator': frontend.validate_comma_separated_list}),
         ('Comma separated list of LaTeX packages/stylesheets. '
          'Relative paths are expanded if a matching file is found in '
          'the --stylesheet-dirs. With --link-stylesheet, '
          'the path is rewritten relative to the output *.tex file. ',
          ['--stylesheet-path'],
          {'metavar': '<file[,file,...]>', 'overrides': 'stylesheet',
           'validator': frontend.validate_comma_separated_list}),
         ('Link to the stylesheet(s) in the output file. (default)',
          ['--link-stylesheet'],
          {'dest': 'embed_stylesheet', 'action': 'store_false'}),
         ('Embed the stylesheet(s) in the output file. '
          'Stylesheets must be accessible during processing. ',
          ['--embed-stylesheet'],
          {'default': False, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Comma-separated list of directories where stylesheets are found. '
          'Used by --stylesheet-path when expanding relative path arguments. '
          'Default: ".".',
          ['--stylesheet-dirs'],
          {'metavar': '<dir[,dir,...]>',
           'validator': frontend.validate_comma_separated_list,
           'default': ['.']}),
         ('Customization by LaTeX code in the preamble. '
          'Default: select PDF standard fonts (Times, Helvetica, Courier).',
          ['--latex-preamble'],
          {'default': default_preamble}),
         ('Specify the template file. Default: "%s".' % default_template,
          ['--template'],
          {'default': default_template, 'metavar': '<file>'}),
         ('Table of contents by LaTeX. (default)',
          ['--use-latex-toc'],
          {'default': True, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Table of contents by Docutils (without page numbers).',
          ['--use-docutils-toc'],
          {'dest': 'use_latex_toc', 'action': 'store_false',
           'validator': frontend.validate_boolean}),
         ('Add parts on top of the section hierarchy.',
          ['--use-part-section'],
          {'default': False, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Attach author and date to the document info table. (default)',
          ['--use-docutils-docinfo'],
          {'dest': 'use_latex_docinfo', 'action': 'store_false',
           'validator': frontend.validate_boolean}),
         ('Attach author and date to the document title.',
          ['--use-latex-docinfo'],
          {'default': False, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ("Typeset abstract as topic. (default)",
          ['--topic-abstract'],
          {'dest': 'use_latex_abstract', 'action': 'store_false',
           'validator': frontend.validate_boolean}),
         ("Use LaTeX abstract environment for the document's abstract.",
          ['--use-latex-abstract'],
          {'default': False, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Color of any hyperlinks embedded in text. '
          'Default: "blue" (use "false" to disable).',
          ['--hyperlink-color'], {'default': 'blue'}),
         ('Additional options to the "hyperref" package.',
          ['--hyperref-options'], {'default': ''}),
         ('Enable compound enumerators for nested enumerated lists '
          '(e.g. "1.2.a.ii").',
          ['--compound-enumerators'],
          {'default': False, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Disable compound enumerators for nested enumerated lists. '
          '(default)',
          ['--no-compound-enumerators'],
          {'action': 'store_false', 'dest': 'compound_enumerators'}),
         ('Enable section ("." subsection ...) prefixes for compound '
          'enumerators.  This has no effect without --compound-enumerators.',
          ['--section-prefix-for-enumerators'],
          {'default': None, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Disable section prefixes for compound enumerators. (default)',
          ['--no-section-prefix-for-enumerators'],
          {'action': 'store_false', 'dest': 'section_prefix_for_enumerators'}),
         ('Set the separator between section number and enumerator '
          'for compound enumerated lists.  Default: "-".',
          ['--section-enumerator-separator'],
          {'default': '-', 'metavar': '<char>'}),
         ('When possible, use the specified environment for literal-blocks. '
          'Default: "" (fall back to "alltt").',
          ['--literal-block-env'],
          {'default': ''}),
         ('When possible, use "verbatim" for literal-blocks. '
          'Compatibility alias for "--literal-block-env=verbatim".',
          ['--use-verbatim-when-possible'],
          {'default': False, 'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Table style. "standard" with horizontal and vertical lines, '
          '"booktabs" (LaTeX booktabs style) only horizontal lines '
          'above and below the table and below the header, or "borderless". '
          'Default: "standard"',
          ['--table-style'],
          {'default': ['standard'],
           'metavar': '<format>',
           'action': 'append',
           'validator': frontend.validate_comma_separated_list,
           'choices': table_style_values}),
         ('LaTeX graphicx package option. '
          'Possible values are "dvipdfmx", "dvips", "dvisvgm", '
          '"luatex", "pdftex", and "xetex".'
          'Default: "".',
          ['--graphicx-option'],
          {'default': ''}),
         ('LaTeX font encoding. '
          'Possible values are "", "T1" (default), "OT1", "LGR,T1" or '
          'any other combination of options to the `fontenc` package. ',
          ['--font-encoding'],
          {'default': 'T1'}),
         ('Per default the latex-writer puts the reference title into '
          'hyperreferences. Specify "ref*" or "pageref*" to get the section '
          'number or the page number.',
          ['--reference-label'],
          {'default': ''}),
         ('Specify style and database for bibtex, for example '
          '"--use-bibtex=mystyle,mydb1,mydb2".',
          ['--use-bibtex'],
          {'default': ''}),
         ('Use legacy functions with class value list for '
          '\\DUtitle and \\DUadmonition (current default). ',
          ['--legacy-class-functions'],
          {'default': True,
           'action': 'store_true',
           'validator': frontend.validate_boolean}),
         ('Use \\DUrole and "DUclass" wrappers for class values. '
          'Place admonition content in an environment (future default).',
          ['--new-class-functions'],
          {'dest': 'legacy_class_functions',
           'action': 'store_false',
           'validator': frontend.validate_boolean}),
         # TODO: implement "latex footnotes" alternative
         ('Footnotes with numbers/symbols by Docutils. (default) '
          '(The alternative, --latex-footnotes, is not implemented yet.)',
           ['--docutils-footnotes'],
           {'default': True,
            'action': 'store_true',
            'validator': frontend.validate_boolean}),
        ),)

    settings_defaults = {'sectnum_depth': 0 # updated by SectNum transform
                        }
    config_section = 'latex2e writer'
    config_section_dependencies = ('writers', 'latex writers')

    head_parts = ('head_prefix', 'requirements', 'latex_preamble',
                  'stylesheet', 'fallbacks', 'pdfsetup', 'titledata')
    visitor_attributes = head_parts + ('title', 'subtitle',
                                       'body_pre_docinfo', 'docinfo',
                                       'dedication', 'abstract', 'body')

    output = None
    """Final translated form of `document`."""

    def __init__(self):
        writers.Writer.__init__(self)
        self.translator_class = LaTeXTranslator

    # Override parent method to add latex-specific transforms
    def get_transforms(self):
       return writers.Writer.get_transforms(self) + [
       # Convert specific admonitions to generic one
       writer_aux.Admonitions,
       # TODO: footnote collection transform
       ]

    def translate(self):
        visitor = self.translator_class(self.document)
        self.document.walkabout(visitor)
        # copy parts
        for part in self.visitor_attributes:
            setattr(self, part, getattr(visitor, part))
        # get template string from file
        try:
            template_file = open(self.document.settings.template,
                                 encoding='utf8')
        except IOError:
            template_file = open(os.path.join(self.default_template_path,
                    self.document.settings.template), encoding= 'utf8')
        template = string.Template(template_file.read())
        template_file.close()
        # fill template
        self.assemble_parts() # create dictionary of parts
        self.output = template.substitute(self.parts)

    def assemble_parts(self):
        """Assemble the `self.parts` dictionary of output fragments."""
        writers.Writer.assemble_parts(self)
        for part in self.visitor_attributes:
            lines = getattr(self, part)
            if part in self.head_parts:
                if lines:
                    lines.append('') # to get a trailing newline
                self.parts[part] = '\n'.join(lines)
            else:
                # body contains inline elements, so join without newline
                self.parts[part] = ''.join(lines)


class Babel(object):
    """Language specifics for LaTeX."""

    # TeX (babel) language names:
    # ! not all of these are supported by Docutils!
    #
    # based on LyX' languages file with adaptions to `BCP 47`_
    # (http://www.rfc-editor.org/rfc/bcp/bcp47.txt) and
    # http://www.tug.org/TUGboat/Articles/tb29-3/tb93miklavec.pdf
    # * the key without subtags is the default
    # * case is ignored
    # cf. http://docutils.sourceforge.net/docs/howto/i18n.html
    #     http://www.w3.org/International/articles/language-tags/
    # and http://www.iana.org/assignments/language-subtag-registry
    language_codes = {
        # code          TeX/Babel-name       comment
        'af':           'afrikaans',
        'ar':           'arabic',
        # 'be':           'belarusian',
        'bg':           'bulgarian',
        'br':           'breton',
        'ca':           'catalan',
        # 'cop':          'coptic',
        'cs':           'czech',
        'cy':           'welsh',
        'da':           'danish',
        'de':           'ngerman', # new spelling (de_1996)
        'de-1901':      'german', # old spelling
        'de-AT':        'naustrian',
        'de-AT-1901':   'austrian',
        'dsb':          'lowersorbian',
        'el':           'greek', # monotonic (el-monoton)
        'el-polyton':   'polutonikogreek',
        'en':           'english',  # TeX' default language
        'en-AU':        'australian',
        'en-CA':        'canadian',
        'en-GB':        'british',
        'en-NZ':        'newzealand',
        'en-US':        'american',
        'eo':           'esperanto',
        'es':           'spanish',
        'et':           'estonian',
        'eu':           'basque',
        # 'fa':           'farsi',
        'fi':           'finnish',
        'fr':           'french',
        'fr-CA':        'canadien',
        'ga':           'irish',    # Irish Gaelic
        # 'grc':                    # Ancient Greek
        'grc-ibycus':   'ibycus',   # Ibycus encoding
        'gl':           'galician',
        'he':           'hebrew',
        'hr':           'croatian',
        'hsb':          'uppersorbian',
        'hu':           'magyar',
        'ia':           'interlingua',
        'id':           'bahasai',  # Bahasa (Indonesian)
        'is':           'icelandic',
        'it':           'italian',
        'ja':           'japanese',
        'kk':           'kazakh',
        'la':           'latin',
        'lt':           'lithuanian',
        'lv':           'latvian',
        'mn':           'mongolian', # Mongolian, Cyrillic script (mn-cyrl)
        'ms':           'bahasam',   # Bahasa (Malay)
        'nb':           'norsk',     # Norwegian Bokmal
        'nl':           'dutch',
        'nn':           'nynorsk',   # Norwegian Nynorsk
        'no':           'norsk',     # Norwegian (Bokmal)
        'pl':           'polish',
        'pt':           'portuges',
        'pt-BR':        'brazil',
        'ro':           'romanian',
        'ru':           'russian',
        'se':           'samin',     # North Sami
        'sh-Cyrl':      'serbianc',  # Serbo-Croatian, Cyrillic script
        'sh-Latn':      'serbian',   # Serbo-Croatian, Latin script see also 'hr'
        'sk':           'slovak',
        'sl':           'slovene',
        'sq':           'albanian',
        'sr':           'serbianc',  # Serbian, Cyrillic script (contributed)
        'sr-Latn':      'serbian',   # Serbian, Latin script
        'sv':           'swedish',
        # 'th':           'thai',
        'tr':           'turkish',
        'uk':           'ukrainian',
        'vi':           'vietnam',
        # zh-Latn:      Chinese Pinyin
        }
    # normalize (downcase) keys
    language_codes = dict([(k.lower(), v) for (k, v) in language_codes.items()])

    warn_msg = 'Language "%s" not supported by LaTeX (babel)'

    # "Active characters" are shortcuts that start a LaTeX macro and may need
    # escaping for literals use. Characters that prevent literal use (e.g.
    # starting accent macros like "a -> ä) will be deactivated if one of the
    # defining languages is used in the document.
    # Special cases:
    #  ~ (tilde) -- used in estonian, basque, galician, and old versions of
    #    spanish -- cannot be deactivated as it denotes a no-break space macro,
    #  " (straight quote) -- used in albanian, austrian, basque
    #    brazil, bulgarian, catalan, czech, danish, dutch, estonian,
    #    finnish, galician, german, icelandic, italian, latin, naustrian,
    #    ngerman, norsk, nynorsk, polish, portuges, russian, serbian, slovak,
    #    slovene, spanish, swedish, ukrainian, and uppersorbian --
    #    is escaped as ``\textquotedbl``.
    active_chars = {# TeX/Babel-name:  active characters to deactivate
                    # 'breton':        ':;!?' # ensure whitespace
                    # 'esperanto':     '^',
                    # 'estonian':      '~"`',
                    # 'french':        ':;!?' # ensure whitespace
                    'galician':        '.<>', # also '~"'
                    # 'magyar':        '`', # for special hyphenation cases
                    'spanish':         '.<>', # old versions also '~'
                    # 'turkish':       ':!=' # ensure whitespace
                   }

    def __init__(self, language_code, reporter=None):
        self.reporter = reporter
        self.language = self.language_name(language_code)
        self.otherlanguages = {}

    def __call__(self):
        """Return the babel call with correct options and settings"""
        languages = sorted(self.otherlanguages.keys())
        languages.append(self.language or 'english')
        self.setup = [r'\usepackage[%s]{babel}' % ','.join(languages)]
        # Deactivate "active characters"
        shorthands = []
        for c in ''.join([self.active_chars.get(l, '') for l in languages]):
            if c not in shorthands:
                shorthands.append(c)
        if shorthands:
            self.setup.append(r'\AtBeginDocument{\shorthandoff{%s}}'
                              % ''.join(shorthands))
        # Including '~' in shorthandoff prevents its use as no-break space
        if 'galician' in languages:
            self.setup.append(r'\deactivatetilden % restore ~ in Galician')
        if 'estonian' in languages:
            self.setup.extend([r'\makeatletter',
                               r'  \addto\extrasestonian{\bbl@deactivate{~}}',
                               r'\makeatother'])
        if 'basque' in languages:
            self.setup.extend([r'\makeatletter',
                               r'  \addto\extrasbasque{\bbl@deactivate{~}}',
                               r'\makeatother'])
        if (languages[-1] == 'english' and
            'french' in self.otherlanguages.keys()):
            self.setup += ['% Prevent side-effects if French hyphenation '
                           'patterns are not loaded:',
                           r'\frenchbsetup{StandardLayout}',
                           r'\AtBeginDocument{\selectlanguage{%s}'
                           r'\noextrasfrench}' % self.language]
        return '\n'.join(self.setup)

    def language_name(self, language_code):
        """Return TeX language name for `language_code`"""
        for tag in utils.normalize_language_tag(language_code):
            try:
                return self.language_codes[tag]
            except KeyError:
                pass
        if self.reporter is not None:
            self.reporter.warning(self.warn_msg % language_code)
        return ''

    def get_language(self):
        # Obsolete, kept for backwards compatibility with Sphinx
        return self.language


# Building blocks for the latex preamble
# --------------------------------------

class SortableDict(dict):
    """Dictionary with additional sorting methods

    Tip: use key starting with with '_' for sorting before small letters
         and with '~' for sorting after small letters.
    """
    def sortedkeys(self):
        """Return sorted list of keys"""
        keys = sorted(self.keys())
        return keys

    def sortedvalues(self):
        """Return list of values sorted by keys"""
        return [self[key] for key in self.sortedkeys()]


# PreambleCmds
# `````````````
# A container for LaTeX code snippets that can be
# inserted into the preamble if required in the document.
#
# .. The package 'makecmds' would enable shorter definitions using the
#    \providelength and \provideenvironment commands.
#    However, it is pretty non-standard (texlive-latex-extra).

class PreambleCmds(object):
    """Building blocks for the latex preamble."""

# Requirements

PreambleCmds.color = r"""\usepackage{color}"""

PreambleCmds.float = r"""\usepackage{float} % extended float configuration
\floatplacement{figure}{H} % place figures here definitely"""

PreambleCmds.linking = r"""%% hyperlinks:
\ifthenelse{\isundefined{\hypersetup}}{
  \usepackage[%s]{hyperref}
  \usepackage{bookmark}
  \urlstyle{same} %% normal text font (alternatives: tt, rm, sf)
}{}"""

PreambleCmds.minitoc = r"""%% local table of contents
\usepackage{minitoc}"""

PreambleCmds.table = r"""\usepackage{longtable,ltcaption,array}
\setlength{\extrarowheight}{2pt}
\newlength{\DUtablewidth} % internal use in tables"""

PreambleCmds.textcomp = r"""\usepackage{textcomp} % text symbol macros"""
# TODO? Options [force,almostfull] prevent spurious error messages,
# see de.comp.text.tex/2005-12/msg01855

# backwards compatibility definitions

PreambleCmds.abstract_legacy = r"""
% abstract title
\providecommand*{\DUtitleabstract}[1]{\centerline{\textbf{#1}}}"""

# see https://sourceforge.net/p/docutils/bugs/339/
PreambleCmds.admonition_legacy = r"""
% admonition (specially marked topic)
\providecommand{\DUadmonition}[2][class-arg]{%
  % try \DUadmonition#1{#2}:
  \ifcsname DUadmonition#1\endcsname%
    \csname DUadmonition#1\endcsname{#2}%
  \else
    \begin{center}
      \fbox{\parbox{0.9\linewidth}{#2}}
    \end{center}
  \fi
}"""

PreambleCmds.error_legacy = r"""
% error admonition title
\providecommand*{\DUtitleerror}[1]{\DUtitle{\color{red}#1}}"""

PreambleCmds.title_legacy = r"""
% title for topics, admonitions, unsupported section levels, and sidebar
\providecommand*{\DUtitle}[2][class-arg]{%
  % call \DUtitle#1{#2} if it exists:
  \ifcsname DUtitle#1\endcsname%
    \csname DUtitle#1\endcsname{#2}%
  \else
    \smallskip\noindent\textbf{#2}\smallskip%
  \fi
}"""

## PreambleCmds.caption = r"""% configure caption layout
## \usepackage{caption}
## \captionsetup{singlelinecheck=false}% no exceptions for one-liners"""


# Definitions from docutils.sty::

def _read_block(fp):
    block = [next(fp)] # first line (empty)
    for line in fp:
        if not line.strip():
            break
        block.append(line)
    return ''.join(block).rstrip()

_du_sty = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                      'docutils.sty')
with open(_du_sty, encoding='utf8') as fp:
    for line in fp:
        line = line.strip('% \n')
        if not line.endswith('::'):
            continue
        block_name = line.rstrip(':')
        if not block_name:
            continue
        definitions = _read_block(fp)
        if block_name in ('color', 'float', 'table', 'textcomp'):
            definitions = definitions.strip()
        # print('Block: `%s`'% block_name)
        # print(definitions)
        setattr(PreambleCmds, block_name, definitions)


# LaTeX encoding maps
# -------------------
# ::

class CharMaps(object):
    """LaTeX representations for active and Unicode characters."""

    # characters that need escaping even in `alltt` environments:
    alltt = {
        ord('\\'): u'\\textbackslash{}',
        ord('{'): u'\\{',
        ord('}'): u'\\}',
    }
    # characters that normally need escaping:
    special = {
        ord('#'): u'\\#',
        ord('$'): u'\\$',
        ord('%'): u'\\%',
        ord('&'): u'\\&',
        ord('~'): u'\\textasciitilde{}',
        ord('_'): u'\\_',
        ord('^'): u'\\textasciicircum{}',
        # straight double quotes are 'active' in many languages
        ord('"'): u'\\textquotedbl{}',
        # Square brackets are ordinary chars and cannot be escaped with '\',
        # so we put them in a group '{[}'. (Alternative: ensure that all
        # macros with optional arguments are terminated with {} and text
        # inside any optional argument is put in a group ``[{text}]``).
        # Commands with optional args inside an optional arg must be put in a
        # group, e.g. ``\item[{\hyperref[label]{text}}]``.
        ord('['): u'{[}',
        ord(']'): u'{]}',
        # the soft hyphen is unknown in 8-bit text
        # and not properly handled by XeTeX
        0x00AD: u'\\-', # SOFT HYPHEN
    }
    # Unicode chars that are not recognized by LaTeX's utf8 encoding
    unsupported_unicode = {
        # TODO: ensure white space also at the beginning of a line?
        # 0x00A0: u'\\leavevmode\\nobreak\\vadjust{}~'
        0x2000: u'\\enskip', # EN QUAD
        0x2001: u'\\quad', # EM QUAD
        0x2002: u'\\enskip', # EN SPACE
        0x2003: u'\\quad', # EM SPACE
        0x2008: u'\\,', # PUNCTUATION SPACE   
        0x200b: u'\\hspace{0pt}', # ZERO WIDTH SPACE
        0x202F: u'\\,', # NARROW NO-BREAK SPACE
        # 0x02d8: u'\\\u{ }', # BREVE
        0x2011: u'\\hbox{-}', # NON-BREAKING HYPHEN
        0x212b: u'\\AA', # ANGSTROM SIGN
        0x21d4: u'\\ensuremath{\\Leftrightarrow}',
        # Docutils footnote symbols:
        0x2660: u'\\ensuremath{\\spadesuit}',
        0x2663: u'\\ensuremath{\\clubsuit}',
        0xfb00: u'ff', # LATIN SMALL LIGATURE FF
        0xfb01: u'fi', # LATIN SMALL LIGATURE FI
        0xfb02: u'fl', # LATIN SMALL LIGATURE FL
        0xfb03: u'ffi', # LATIN SMALL LIGATURE FFI
        0xfb04: u'ffl', # LATIN SMALL LIGATURE FFL
    }
    # Unicode chars that are recognized by LaTeX's utf8 encoding
    utf8_supported_unicode = {
        0x00A0: u'~', # NO-BREAK SPACE
        0x00AB: u'\\guillemotleft{}', # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
        0x00bb: u'\\guillemotright{}', # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
        0x200C: u'\\textcompwordmark{}', # ZERO WIDTH NON-JOINER
        0x2013: u'\\textendash{}',
        0x2014: u'\\textemdash{}',
        0x2018: u'\\textquoteleft{}',
        0x2019: u'\\textquoteright{}',
        0x201A: u'\\quotesinglbase{}', # SINGLE LOW-9 QUOTATION MARK
        0x201C: u'\\textquotedblleft{}',
        0x201D: u'\\textquotedblright{}',
        0x201E: u'\\quotedblbase{}', # DOUBLE LOW-9 QUOTATION MARK
        0x2030: u'\\textperthousand{}',   # PER MILLE SIGN
        0x2031: u'\\textpertenthousand{}', # PER TEN THOUSAND SIGN
        0x2039: u'\\guilsinglleft{}',
        0x203A: u'\\guilsinglright{}',
        0x2423: u'\\textvisiblespace{}',  # OPEN BOX
        0x2020: u'\\dag{}',
        0x2021: u'\\ddag{}',
        0x2026: u'\\dots{}',
        0x2122: u'\\texttrademark{}',
    }
    # recognized with 'utf8', if textcomp is loaded
    textcomp = {
        # Latin-1 Supplement
        0x00a2: u'\\textcent{}',          # ¢ CENT SIGN
        0x00a4: u'\\textcurrency{}',      # ¤ CURRENCY SYMBOL
        0x00a5: u'\\textyen{}',           # ¥ YEN SIGN
        0x00a6: u'\\textbrokenbar{}',     # ¦ BROKEN BAR
        0x00a7: u'\\textsection{}',       # § SECTION SIGN
        0x00a8: u'\\textasciidieresis{}', # ¨ DIAERESIS
        0x00a9: u'\\textcopyright{}',     # © COPYRIGHT SIGN
        0x00aa: u'\\textordfeminine{}',   # ª FEMININE ORDINAL INDICATOR
        0x00ac: u'\\textlnot{}',          # ¬ NOT SIGN
        0x00ae: u'\\textregistered{}',    # ® REGISTERED SIGN
        0x00af: u'\\textasciimacron{}',   # ¯ MACRON
        0x00b0: u'\\textdegree{}',        # ° DEGREE SIGN
        0x00b1: u'\\textpm{}',            # ± PLUS-MINUS SIGN
        0x00b2: u'\\texttwosuperior{}',   # ² SUPERSCRIPT TWO
        0x00b3: u'\\textthreesuperior{}', # ³ SUPERSCRIPT THREE
        0x00b4: u'\\textasciiacute{}',    # ´ ACUTE ACCENT
        0x00b5: u'\\textmu{}',            # µ MICRO SIGN
        0x00b6: u'\\textparagraph{}',     # ¶ PILCROW SIGN # != \textpilcrow
        0x00b9: u'\\textonesuperior{}',   # ¹ SUPERSCRIPT ONE
        0x00ba: u'\\textordmasculine{}',  # º MASCULINE ORDINAL INDICATOR
        0x00bc: u'\\textonequarter{}',    # 1/4 FRACTION
        0x00bd: u'\\textonehalf{}',       # 1/2 FRACTION
        0x00be: u'\\textthreequarters{}', # 3/4 FRACTION
        0x00d7: u'\\texttimes{}',         # × MULTIPLICATION SIGN
        0x00f7: u'\\textdiv{}',           # ÷ DIVISION SIGN
        # others
        0x0192: u'\\textflorin{}',        # LATIN SMALL LETTER F WITH HOOK
        0x02b9: u'\\textasciiacute{}',    # MODIFIER LETTER PRIME
        0x02ba: u'\\textacutedbl{}',      # MODIFIER LETTER DOUBLE PRIME
        0x2016: u'\\textbardbl{}',        # DOUBLE VERTICAL LINE
        0x2022: u'\\textbullet{}',        # BULLET
        0x2032: u'\\textasciiacute{}',    # PRIME
        0x2033: u'\\textacutedbl{}',      # DOUBLE PRIME
        0x2035: u'\\textasciigrave{}',    # REVERSED PRIME
        0x2036: u'\\textgravedbl{}',      # REVERSED DOUBLE PRIME
        0x203b: u'\\textreferencemark{}', # REFERENCE MARK
        0x203d: u'\\textinterrobang{}',   # INTERROBANG
        0x2044: u'\\textfractionsolidus{}', # FRACTION SLASH
        0x2045: u'\\textlquill{}',        # LEFT SQUARE BRACKET WITH QUILL
        0x2046: u'\\textrquill{}',        # RIGHT SQUARE BRACKET WITH QUILL
        0x2052: u'\\textdiscount{}',      # COMMERCIAL MINUS SIGN
        0x20a1: u'\\textcolonmonetary{}', # COLON SIGN
        0x20a3: u'\\textfrenchfranc{}',   # FRENCH FRANC SIGN
        0x20a4: u'\\textlira{}',          # LIRA SIGN
        0x20a6: u'\\textnaira{}',         # NAIRA SIGN
        0x20a9: u'\\textwon{}',           # WON SIGN
        0x20ab: u'\\textdong{}',          # DONG SIGN
        0x20ac: u'\\texteuro{}',          # EURO SIGN
        0x20b1: u'\\textpeso{}',          # PESO SIGN
        0x20b2: u'\\textguarani{}',       # GUARANI SIGN
        0x2103: u'\\textcelsius{}',       # DEGREE CELSIUS
        0x2116: u'\\textnumero{}',        # NUMERO SIGN
        0x2117: u'\\textcircledP{}',      # SOUND RECORDING COYRIGHT
        0x211e: u'\\textrecipe{}',        # PRESCRIPTION TAKE
        0x2120: u'\\textservicemark{}',   # SERVICE MARK
        0x2122: u'\\texttrademark{}',     # TRADE MARK SIGN
        0x2126: u'\\textohm{}',           # OHM SIGN
        0x2127: u'\\textmho{}',           # INVERTED OHM SIGN
        0x212e: u'\\textestimated{}',     # ESTIMATED SYMBOL
        0x2190: u'\\textleftarrow{}',     # LEFTWARDS ARROW
        0x2191: u'\\textuparrow{}',       # UPWARDS ARROW
        0x2192: u'\\textrightarrow{}',    # RIGHTWARDS ARROW
        0x2193: u'\\textdownarrow{}',     # DOWNWARDS ARROW
        0x2212: u'\\textminus{}',         # MINUS SIGN
        0x2217: u'\\textasteriskcentered{}', # ASTERISK OPERATOR
        0x221a: u'\\textsurd{}',          # SQUARE ROOT
        0x2422: u'\\textblank{}',         # BLANK SYMBOL
        0x25e6: u'\\textopenbullet{}',    # WHITE BULLET
        0x25ef: u'\\textbigcircle{}',     # LARGE CIRCLE
        0x266a: u'\\textmusicalnote{}',   # EIGHTH NOTE
        0x26ad: u'\\textmarried{}',       # MARRIAGE SYMBOL
        0x26ae: u'\\textdivorced{}',      # DIVORCE SYMBOL
        0x27e8: u'\\textlangle{}',        # MATHEMATICAL LEFT ANGLE BRACKET
        0x27e9: u'\\textrangle{}',        # MATHEMATICAL RIGHT ANGLE BRACKET
    }
    # Unicode chars that require a feature/package to render
    pifont = {
        0x2665: u'\\ding{170}',     # black heartsuit
        0x2666: u'\\ding{169}',     # black diamondsuit
        0x2713: u'\\ding{51}',      # check mark
        0x2717: u'\\ding{55}',      # check mark
    }
    # TODO: greek alphabet ... ?
    # see also LaTeX codec
    # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/252124
    # and unimap.py from TeXML


class DocumentClass(object):
    """Details of a LaTeX document class."""

    def __init__(self, document_class, with_part=False):
        self.document_class = document_class
        self._with_part = with_part
        self.sections = ['section', 'subsection', 'subsubsection',
                         'paragraph', 'subparagraph']
        if self.document_class in ('book', 'memoir', 'report',
                                   'scrbook', 'scrreprt'):
            self.sections.insert(0, 'chapter')
        if self._with_part:
            self.sections.insert(0, 'part')

    def section(self, level):
        """Return the LaTeX section name for section `level`.

        The name depends on the specific document class.
        Level is 1,2,3..., as level 0 is the title.
        """
        if level <= len(self.sections):
            return self.sections[level-1]
        # unsupported levels
        return 'DUtitle'


class Table(object):
    """Manage a table while traversing.

    Maybe change to a mixin defining the visit/departs, but then
    class Table internal variables are in the Translator.

    Table style might be

    :standard:   horizontal and vertical lines
    :booktabs:   only horizontal lines (requires "booktabs" LaTeX package)
    :borderless: no borders around table cells
    :nolines:    alias for borderless

    :colwidths-auto:  column widths determined by LaTeX
    :colwidths-given: use colum widths from rST source
    """
    def __init__(self, translator, latex_type):
        self._translator = translator
        self._latex_type = latex_type
        self._open = False
        # miscellaneous attributes
        self._attrs = {}
        self._col_width = []
        self._rowspan = []
        self.stubs = []
        self.colwidths_auto = False
        self._in_thead = 0

    def open(self):
        self._open = True
        self._col_specs = []
        self.caption = []
        self._attrs = {}
        self._in_head = False # maybe context with search
    def close(self):
        self._open = False
        self._col_specs = None
        self.caption = []
        self._attrs = {}
        self.stubs = []
        self.colwidths_auto = False

    def is_open(self):
        return self._open

    def set_table_style(self, table_style, classes):
        borders = [cls.replace('nolines', 'borderless')
                   for cls in table_style+classes
                   if cls in ('standard', 'booktabs', 'borderless', 'nolines')]
        try:
            self.borders = borders[-1]
        except IndexError:
            self.borders = 'standard'
        self.colwidths_auto = (('colwidths-auto' in classes
                                and 'colwidths-given' not in table_style)
                               or ('colwidths-auto' in table_style
                                   and ('colwidths-given' not in classes)))

    def get_latex_type(self):
        if self._latex_type == 'longtable' and not self.caption:
            # do not advance the "table" counter (requires "ltcaption" package)
            return('longtable*')
        return self._latex_type

    def set(self, attr, value):
        self._attrs[attr] = value
    def get(self, attr):
        if attr in self._attrs:
            return self._attrs[attr]
        return None

    def get_vertical_bar(self):
        if self.borders == 'standard':
            return '|'
        return ''

    # horizontal lines are drawn below a row,
    def get_opening(self, width=r'\linewidth'):
        align_map = {'left': '[l]',
                     'center': '[c]',
                     'right': '[r]',
                     None: ''}
        align = align_map.get(self.get('align'))
        latex_type = self.get_latex_type()
        if align and latex_type not in ("longtable", "longtable*"):
            opening = [r'\noindent\makebox[\linewidth]%s{%%' % (align,),
                       r'\begin{%s}' % (latex_type,),
                      ]
        else:
            opening = [r'\begin{%s}%s' % (latex_type, align)]
        if not self.colwidths_auto:
            opening.insert(-1, r'\setlength{\DUtablewidth}{%s}%%'%width)
        return '\n'.join(opening)

    def get_closing(self):
        closing = []
        if self.borders == 'booktabs':
            closing.append(r'\bottomrule')
        # elif self.borders == 'standard':
        #     closing.append(r'\hline')
        closing.append(r'\end{%s}' % self.get_latex_type())
        if self.get('align') and self.get_latex_type() not in ("longtable", "longtable*"):
            closing.append('}')
        return '\n'.join(closing)

    def visit_colspec(self, node):
        self._col_specs.append(node)
        # "stubs" list is an attribute of the tgroup element:
        self.stubs.append(node.attributes.get('stub'))

    def get_colspecs(self, node):
        """Return column specification for longtable.

        Assumes reST line length being 80 characters.
        Table width is hairy.

        === ===
        ABC DEF
        === ===

        usually gets to narrow, therefore we add 1 (fiddlefactor).
        """
        bar = self.get_vertical_bar()
        self._rowspan= [0] * len(self._col_specs)
        self._col_width = []
        if self.colwidths_auto:
            latex_table_spec = (bar+'l')*len(self._col_specs)
            return latex_table_spec+bar
        width = 80
        total_width = 0.0
        # first see if we get too wide.
        for node in self._col_specs:
            colwidth = float(node['colwidth']+1) / width
            total_width += colwidth
        # donot make it full linewidth
        factor = 0.93
        if total_width > 1.0:
            factor /= total_width
        latex_table_spec = ''
        for node in self._col_specs:
            colwidth = factor * float(node['colwidth']+1) / width
            self._col_width.append(colwidth+0.005)
            latex_table_spec += '%sp{%.3f\\DUtablewidth}' % (bar, colwidth+0.005)
        return latex_table_spec+bar

    def get_column_width(self):
        """Return columnwidth for current cell (not multicell)."""
        try:
            return '%.2f\\DUtablewidth' % self._col_width[self._cell_in_row]
        except IndexError:
            return '*'

    def get_multicolumn_width(self, start, len_):
        """Return sum of columnwidths for multicell."""
        try:
            mc_width = sum([width
                            for width in ([self._col_width[start + co]
                                           for co in range (len_)])])
            return 'p{%.2f\\DUtablewidth}' % mc_width
        except IndexError:
            return 'l'

    def get_caption(self):
        if not self.caption:
            return ''
        caption = ''.join(self.caption)
        if 1 == self._translator.thead_depth():
            return r'\caption{%s}\\' '\n' % caption
        return r'\caption[]{%s (... continued)}\\' '\n' % caption

    def need_recurse(self):
        if self._latex_type == 'longtable':
            return 1 == self._translator.thead_depth()
        return 0

    def visit_thead(self):
        self._in_thead += 1
        if self.borders == 'standard':
            return ['\\hline\n']
        elif self.borders == 'booktabs':
            return ['\\toprule\n']
        return []

    def depart_thead(self):
        a = []
        #if self.borders == 'standard':
        #    a.append('\\hline\n')
        if self.borders == 'booktabs':
            a.append('\\midrule\n')
        if self._latex_type == 'longtable':
            if 1 == self._translator.thead_depth():
                a.append('\\endfirsthead\n')
            else:
                a.append('\\endhead\n')
                a.append(r'\multicolumn{%d}{c}' % len(self._col_specs) +
                         r'{\hfill ... continued on next page} \\')
                a.append('\n\\endfoot\n\\endlastfoot\n')
        # for longtable one could add firsthead, foot and lastfoot
        self._in_thead -= 1
        return a

    def visit_row(self):
        self._cell_in_row = 0

    def depart_row(self):
        res = [' \\\\\n']
        self._cell_in_row = None  # remove cell counter
        for i in range(len(self._rowspan)):
            if (self._rowspan[i]>0):
                self._rowspan[i] -= 1

        if self.borders == 'standard':
            rowspans = [i+1 for i in range(len(self._rowspan))
                        if (self._rowspan[i]<=0)]
            if len(rowspans)==len(self._rowspan):
                res.append('\\hline\n')
            else:
                cline = ''
                rowspans.reverse()
                # TODO merge clines
                while True:
                    try:
                        c_start = rowspans.pop()
                    except:
                        break
                    cline += '\\cline{%d-%d}\n' % (c_start, c_start)
                res.append(cline)
        return res

    def set_rowspan(self, cell, value):
        try:
            self._rowspan[cell] = value
        except:
            pass

    def get_rowspan(self, cell):
        try:
            return self._rowspan[cell]
        except:
            return 0

    def get_entry_number(self):
        return self._cell_in_row

    def visit_entry(self):
        self._cell_in_row += 1

    def is_stub_column(self):
        if len(self.stubs) >= self._cell_in_row:
            return self.stubs[self._cell_in_row]
        return False


class LaTeXTranslator(nodes.NodeVisitor):
    """
    Generate code for 8-bit LaTeX from a Docutils document tree.

    See the docstring of docutils.writers._html_base.HTMLTranslator for
    notes on and examples of safe subclassing.
    """

    # When options are given to the documentclass, latex will pass them
    # to other packages, as done with babel.
    # Dummy settings might be taken from document settings

    # Generate code for typesetting with 8-bit latex/pdflatex vs.
    # xelatex/lualatex engine. Overwritten by the XeTeX writer
    is_xetex = False

    # Config setting defaults
    # -----------------------

    # TODO: use mixins for different implementations.
    # list environment for docinfo. else tabularx
    ## use_optionlist_for_docinfo = False # TODO: NOT YET IN USE

    # Use compound enumerations (1.A.1.)
    compound_enumerators = False

    # If using compound enumerations, include section information.
    section_prefix_for_enumerators = False

    # This is the character that separates the section ("." subsection ...)
    # prefix from the regular list enumerator.
    section_enumerator_separator = '-'

    # Auxiliary variables
    # -------------------

    has_latex_toc = False # is there a toc in the doc? (needed by minitoc)
    is_toc_list = False   # is the current bullet_list a ToC?
    section_level = 0

    # Flags to encode():
    # inside citation reference labels underscores dont need to be escaped
    inside_citation_reference_label = False
    verbatim = False                   # do not encode
    insert_non_breaking_blanks = False # replace blanks by "~"
    insert_newline = False             # add latex newline commands
    literal = False                    # literal text (block or inline)
    alltt = False                      # inside `alltt` environment

    def __init__(self, document, babel_class=Babel):
        nodes.NodeVisitor.__init__(self, document)
        # Reporter
        # ~~~~~~~~
        self.warn = self.document.reporter.warning
        self.error = self.document.reporter.error

        # Settings
        # ~~~~~~~~
        self.settings = settings = document.settings
        self.latex_encoding = self.to_latex_encoding(settings.output_encoding)
        self.use_latex_toc = settings.use_latex_toc
        self.use_latex_docinfo = settings.use_latex_docinfo
        self._use_latex_citations = settings.use_latex_citations
        self._reference_label = settings.reference_label
        self.hyperlink_color = settings.hyperlink_color
        self.compound_enumerators = settings.compound_enumerators
        self.font_encoding = getattr(settings, 'font_encoding', '')
        self.section_prefix_for_enumerators = (
            settings.section_prefix_for_enumerators)
        self.section_enumerator_separator = (
            settings.section_enumerator_separator.replace('_', r'\_'))
        # literal blocks:
        self.literal_block_env = ''
        self.literal_block_options = ''
        if settings.literal_block_env:
            (none,
             self.literal_block_env,
             self.literal_block_options,
             none) = re.split(r'(\w+)(.*)', settings.literal_block_env)
        elif settings.use_verbatim_when_possible:
            self.literal_block_env = 'verbatim'
        #
        if self.settings.use_bibtex:
            self.bibtex = self.settings.use_bibtex.split(',', 1)
            # TODO avoid errors on not declared citations.
        else:
            self.bibtex = None
        # language module for Docutils-generated text
        # (labels, bibliographic_fields, and author_separators)
        self.language_module = languages.get_language(settings.language_code,
                                              document.reporter)
        self.babel = babel_class(settings.language_code, document.reporter)
        self.author_separator = self.language_module.author_separators[0]
        d_options = [self.settings.documentoptions]
        if self.babel.language not in ('english', ''):
            d_options.append(self.babel.language)
        self.documentoptions = ','.join(filter(None, d_options))
        self.d_class = DocumentClass(settings.documentclass,
                                     settings.use_part_section)
        # graphic package options:
        if self.settings.graphicx_option == '':
            self.graphicx_package = r'\usepackage{graphicx}'
        else:
            self.graphicx_package = (r'\usepackage[%s]{graphicx}' %
                                     self.settings.graphicx_option)
        # footnotes: TODO: implement LaTeX footnotes
        self.docutils_footnotes = settings.docutils_footnotes
        # @@ table_style: list of values from fixed set: warn?
        # for s in self.settings.table_style:
        #     if s not in Writer.table_style_values:
        #         self.warn('Ignoring value "%s" in "table-style" setting.' %s)

        # Output collection stacks
        # ~~~~~~~~~~~~~~~~~~~~~~~~

        # Document parts
        self.head_prefix = [r'\documentclass[%s]{%s}' %
            (self.documentoptions, self.settings.documentclass)]
        self.requirements = SortableDict() # made a list in depart_document()
        self.requirements['__static'] = r'\usepackage{ifthen}'
        self.latex_preamble = [settings.latex_preamble]
        self.fallbacks = SortableDict() # made a list in depart_document()
        self.pdfsetup = [] # PDF properties (hyperref package)
        self.title = []
        self.subtitle = []
        self.titledata = [] # \title, \author, \date
        ## self.body_prefix = ['\\begin{document}\n']
        self.body_pre_docinfo = [] # \maketitle
        self.docinfo = []
        self.dedication = []
        self.abstract = []
        self.body = []
        ## self.body_suffix = ['\\end{document}\n']

        self.context = []
        """Heterogeneous stack.

        Used by visit_* and depart_* functions in conjunction with the tree
        traversal. Make sure that the pops correspond to the pushes."""

        # Title metadata:
        self.title_labels = []
        self.subtitle_labels = []
        # (if use_latex_docinfo: collects lists of
        # author/organization/contact/address lines)
        self.author_stack = []
        self.date = []

        # PDF properties: pdftitle, pdfauthor
        self.pdfauthor = []
        self.pdfinfo = []
        if settings.language_code != 'en':
            self.pdfinfo.append('  pdflang={%s},'%settings.language_code)

        # Stack of section counters so that we don't have to use_latex_toc.
        # This will grow and shrink as processing occurs.
        # Initialized for potential first-level sections.
        self._section_number = [0]

        # The current stack of enumerations so that we can expand
        # them into a compound enumeration.
        self._enumeration_counters = []
        # The maximum number of enumeration counters we've used.
        # If we go beyond this number, we need to create a new
        # counter; otherwise, just reuse an old one.
        self._max_enumeration_counters = 0

        self._bibitems = []

        # object for a table while proccessing.
        self.table_stack = []
        self.active_table = Table(self, 'longtable')

        # Where to collect the output of visitor methods (default: body)
        self.out = self.body
        self.out_stack = []  # stack of output collectors

        # Process settings
        # ~~~~~~~~~~~~~~~~
        # Encodings:
        # Docutils' output-encoding => TeX input encoding
        if self.latex_encoding != 'ascii':
            self.requirements['_inputenc'] = (r'\usepackage[%s]{inputenc}'
                                              % self.latex_encoding)
        # TeX font encoding
        if not self.is_xetex:
            if self.font_encoding:
                self.requirements['_fontenc'] = (r'\usepackage[%s]{fontenc}' %
                                                 self.font_encoding)
            # ensure \textquotedbl is defined:
            for enc in self.font_encoding.split(','):
                enc = enc.strip()
                if enc == 'OT1':
                    self.requirements['_textquotedblOT1'] = (
                        r'\DeclareTextSymbol{\textquotedbl}{OT1}{`\"}')
                elif enc not in ('T1', 'T2A', 'T2B', 'T2C', 'T4', 'T5'):
                    self.requirements['_textquotedbl'] = (
                        r'\DeclareTextSymbolDefault{\textquotedbl}{T1}')
        # page layout with typearea (if there are relevant document options)
        if (settings.documentclass.find('scr') == -1 and
            (self.documentoptions.find('DIV') != -1 or
             self.documentoptions.find('BCOR') != -1)):
            self.requirements['typearea'] = r'\usepackage{typearea}'

        # Stylesheets
        # (the name `self.stylesheet` is singular because only one
        # stylesheet was supported before Docutils 0.6).
        stylesheet_list = utils.get_stylesheet_list(settings)
        self.fallback_stylesheet = 'docutils' in stylesheet_list
        if self.fallback_stylesheet:
            stylesheet_list = [sheet for sheet in stylesheet_list
                               if sheet != 'docutils']
            if self.settings.legacy_class_functions:
                # docutils.sty is incompatible with legacy functions
                self.fallback_stylesheet = False
            else:
                # require a minimal version:
                self.fallbacks['docutils.sty'
                              ] = r'\usepackage{docutils}[2020/08/28]'

        self.stylesheet = [self.stylesheet_call(path)
                           for path in stylesheet_list]

        # PDF setup
        if self.hyperlink_color in ('0', 'false', 'False', ''):
            self.hyperref_options = ''
        else:
            self.hyperref_options = 'colorlinks=true,linkcolor=%s,urlcolor=%s' % (
                                      self.hyperlink_color, self.hyperlink_color)
        if settings.hyperref_options:
            self.hyperref_options += ',' + settings.hyperref_options

        # LaTeX Toc
        # include all supported sections in toc and PDF bookmarks
        # (or use documentclass-default (as currently))?
        ## if self.use_latex_toc:
        ##    self.requirements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
        ##                                     len(self.d_class.sections))

        # Section numbering
        if settings.sectnum_xform: # section numbering by Docutils
            PreambleCmds.secnumdepth = r'\setcounter{secnumdepth}{0}'
        else: # section numbering by LaTeX:
            secnumdepth = settings.sectnum_depth
            # Possible values of settings.sectnum_depth:
            # None  "sectnum" directive without depth arg -> LaTeX default
            #  0    no "sectnum" directive -> no section numbers
            # >0    value of "depth" argument -> translate to LaTeX levels:
            #       -1  part    (0 with "article" document class)
            #        0  chapter (missing in "article" document class)
            #        1  section
            #        2  subsection
            #        3  subsubsection
            #        4  paragraph
            #        5  subparagraph
            if secnumdepth is not None:
                # limit to supported levels
                secnumdepth = min(secnumdepth, len(self.d_class.sections))
                # adjust to document class and use_part_section settings
                if 'chapter' in  self.d_class.sections:
                    secnumdepth -= 1
                if self.d_class.sections[0] == 'part':
                    secnumdepth -= 1
                PreambleCmds.secnumdepth = \
                    r'\setcounter{secnumdepth}{%d}' % secnumdepth

            # start with specified number:
            if (hasattr(settings, 'sectnum_start') and
                settings.sectnum_start != 1):
                self.requirements['sectnum_start'] = (
                    r'\setcounter{%s}{%d}' % (self.d_class.sections[0],
                                              settings.sectnum_start-1))
            # TODO: currently ignored (configure in a stylesheet):
            ## settings.sectnum_prefix
            ## settings.sectnum_suffix

    # Auxiliary Methods
    # -----------------

    def stylesheet_call(self, path):
        """Return code to reference or embed stylesheet file `path`"""
        # is it a package (no extension or *.sty) or "normal" tex code:
        (base, ext) = os.path.splitext(path)
        is_package = ext in ['.sty', '']
        # Embed content of style file:
        if self.settings.embed_stylesheet:
            if is_package:
                path = base + '.sty' # ensure extension
            try:
                content = docutils.io.FileInput(source_path=path,
                                       encoding='utf-8').read()
                self.settings.record_dependencies.add(path)
            except IOError as err:
                msg = u'Cannot embed stylesheet %r:\n  %s.' % (
                                path, SafeString(err.strerror))
                self.document.reporter.error(msg)
                return '% ' + msg.replace('\n', '\n% ')
            if is_package:
                content = '\n'.join([r'\makeatletter',
                                     content,
                                     r'\makeatother'])
            return '%% embedded stylesheet: %s\n%s' % (path, content)
        # Link to style file:
        if is_package:
            path = base # drop extension
            cmd = r'\usepackage{%s}'
        else:
            cmd = r'\input{%s}'
        if self.settings.stylesheet_path:
            # adapt path relative to output (cf. config.html#stylesheet-path)
            path = utils.relative_path(self.settings._destination, path)
        return cmd % path

    def to_latex_encoding(self, docutils_encoding):
        """Translate docutils encoding name into LaTeX's.

        Default method is remove "-" and "_" chars from docutils_encoding.
        """
        tr = {  'iso-8859-1': 'latin1',     # west european
                'iso-8859-2': 'latin2',     # east european
                'iso-8859-3': 'latin3',     # esperanto, maltese
                'iso-8859-4': 'latin4',     # north european, scandinavian, baltic
                'iso-8859-5': 'iso88595',   # cyrillic (ISO)
                'iso-8859-9': 'latin5',     # turkish
                'iso-8859-15': 'latin9',    # latin9, update to latin1.
                'mac_cyrillic': 'maccyr',   # cyrillic (on Mac)
                'windows-1251': 'cp1251',   # cyrillic (on Windows)
                'koi8-r': 'koi8-r',         # cyrillic (Russian)
                'koi8-u': 'koi8-u',         # cyrillic (Ukrainian)
                'windows-1250': 'cp1250',   #
                'windows-1252': 'cp1252',   #
                'us-ascii': 'ascii',        # ASCII (US)
                # unmatched encodings
                #'': 'applemac',
                #'': 'ansinew',  # windows 3.1 ansi
                #'': 'ascii',    # ASCII encoding for the range 32--127.
                #'': 'cp437',    # dos latin us
                #'': 'cp850',    # dos latin 1
                #'': 'cp852',    # dos latin 2
                #'': 'decmulti',
                #'': 'latin10',
                #'iso-8859-6': ''   # arabic
                #'iso-8859-7': ''   # greek
                #'iso-8859-8': ''   # hebrew
                #'iso-8859-10': ''   # latin6, more complete iso-8859-4
             }
        encoding = docutils_encoding.lower()
        if encoding in tr:
            return tr[encoding]
        # drop hyphen or low-line from "latin-1", "latin_1", "utf-8" and similar
        encoding = encoding.replace('_', '').replace('-', '')
        # strip the error handler
        return encoding.split(':')[0]

    def language_label(self, docutil_label):
        return self.language_module.labels[docutil_label]

    def encode(self, text):
        """Return text with 'problematic' characters escaped.

        * Escape the special printing characters ``# $ % & ~ _ ^ \\ { }``,
          square brackets ``[ ]``, double quotes and (in OT1) ``< | >``.
        * Translate non-supported Unicode characters.
        * Separate ``-`` (and more in literal text) to prevent input ligatures.
        """
        if self.verbatim:
            return text
        # Set up the translation table:
        table = CharMaps.alltt.copy()
        if not self.alltt:
            table.update(CharMaps.special)
        # keep the underscore in citation references
        if self.inside_citation_reference_label and not self.alltt:
            del(table[ord('_')])
        # Workarounds for OT1 font-encoding
        if self.font_encoding in ['OT1', ''] and not self.is_xetex:
            # * out-of-order characters in cmtt
            if self.literal:
                # replace underscore by underlined blank,
                # because this has correct width.
                table[ord('_')] = u'\\underline{~}'
                # the backslash doesn't work, so we use a mirrored slash.
                # \reflectbox is provided by graphicx:
                self.requirements['graphicx'] = self.graphicx_package
                table[ord('\\')] = u'\\reflectbox{/}'
            # * ``< | >`` come out as different chars (except for cmtt):
            else:
                table[ord('|')] = u'\\textbar{}'
                table[ord('<')] = u'\\textless{}'
                table[ord('>')] = u'\\textgreater{}'
        if self.insert_non_breaking_blanks:
            table[ord(' ')] = u'~'
            # tab chars may occur in included files (literal or code)
            # quick-and-dirty replacement with spaces
            # (for better results use `--literal-block-env=lstlisting`)
            table[ord('\t')] = u'~' * self.settings.tab_width
        # Unicode replacements for 8-bit tex engines (not required with XeTeX/LuaTeX):
        if not self.is_xetex:
            if not self.latex_encoding.startswith('utf8'):
                table.update(CharMaps.unsupported_unicode)
                table.update(CharMaps.utf8_supported_unicode)
                table.update(CharMaps.textcomp)
            table.update(CharMaps.pifont)
            # Characters that require a feature/package to render
            for ch in text:
                cp = ord(ch)
                if cp in CharMaps.textcomp and not self.fallback_stylesheet:
                    self.requirements['textcomp'] = PreambleCmds.textcomp
                elif cp in CharMaps.pifont:
                    self.requirements['pifont'] = '\\usepackage{pifont}'
                # preamble-definitions for unsupported Unicode characters
                elif (self.latex_encoding == 'utf8'
                      and cp in CharMaps.unsupported_unicode):
                    self.requirements['_inputenc'+str(cp)] = (
                        '\\DeclareUnicodeCharacter{%04X}{%s}'
                         % (cp, CharMaps.unsupported_unicode[cp]))
        text = text.translate(table)

        # Break up input ligatures e.g. '--' to '-{}-'.
        if not self.is_xetex: # Not required with xetex/luatex
            separate_chars = '-'
            # In monospace-font, we also separate ',,', '``' and "''" and some
            # other characters which can't occur in non-literal text.
            if self.literal:
                separate_chars += ',`\'"<>'
            for char in separate_chars * 2:
                # Do it twice ("* 2") because otherwise we would replace
                # '---' by '-{}--'.
                text = text.replace(char + char, char + '{}' + char)

        # Literal line breaks (in address or literal blocks):
        if self.insert_newline:
            lines = text.split('\n')
            # Add a protected space to blank lines (except the last)
            # to avoid ``! LaTeX Error: There's no line here to end.``
            for i, line in enumerate(lines[:-1]):
                if not line.lstrip():
                    lines[i] += '~'
            text = (r'\\' + '\n').join(lines)
        if self.literal and not self.insert_non_breaking_blanks:
            # preserve runs of spaces but allow wrapping
            text = text.replace('  ', ' ~')
        return text

    def attval(self, text,
               whitespace=re.compile('[\n\r\t\v\f]')):
        """Cleanse, encode, and return attribute value text."""
        return self.encode(whitespace.sub(' ', text))

    # TODO: is this used anywhere? -> update (use template) or delete
    ## def astext(self):
    ##     """Assemble document parts and return as string."""
    ##     head = '\n'.join(self.head_prefix + self.stylesheet + self.head)
    ##     body = ''.join(self.body_prefix  + self.body + self.body_suffix)
    ##     return head + '\n' + body

    def is_inline(self, node):
        """Check whether a node represents an inline or block-level element"""
        return isinstance(node.parent, nodes.TextElement)

    def append_hypertargets(self, node):
        """Append hypertargets for all ids of `node`"""
        # hypertarget places the anchor at the target's baseline,
        # so we raise it explicitely
        self.out.append('%\n'.join(['\\raisebox{1em}{\\hypertarget{%s}{}}' %
                                    id for id in node['ids']]))

    def ids_to_labels(self, node, set_anchor=True, protect=False):
        """Return list of label definitions for all ids of `node`

        If `set_anchor` is True, an anchor is set with \\phantomsection.
        If `protect` is True, the \\label cmd is made robust.
        """
        labels = ['\\label{%s}' % id for id in node.get('ids', [])]
        if protect:
            labels = ['\\protect'+label for label in labels]
        if set_anchor and labels:
            labels.insert(0, '\\phantomsection')
        return labels

    def set_align_from_classes(self, node):
        """Convert ``align-*`` class arguments into alignment args."""
        # separate:
        align = [cls for cls in node['classes'] if cls.startswith('align-')]
        if align:
            node['align'] = align[-1].replace('align-', '')
            node['classes'] = [cls for cls in node['classes']
                               if not cls.startswith('align-')]

    def insert_align_declaration(self, node, default=None):
        align = node.get('align', default)
        if align == 'left':
            self.out.append('\\raggedright\n')
        elif align == 'center':
            self.out.append('\\centering\n')
        elif align == 'right':
            self.out.append('\\raggedleft\n')

    def duclass_open(self, node):
        """Open a group and insert declarations for class values."""
        if not isinstance(node.parent, nodes.compound):
             self.out.append('\n')
        for cls in node['classes']:
            if cls.startswith('language-'):
                language = self.babel.language_name(cls[9:])
                if language:
                    self.babel.otherlanguages[language] = True
                    self.out.append('\\begin{selectlanguage}{%s}\n' % language)
            elif isinstance(node, nodes.table) and cls in Writer.table_style_values:
                pass
            else:
                if not self.fallback_stylesheet:
                    self.fallbacks['DUclass'] = PreambleCmds.duclass
                self.out.append('\\begin{DUclass}{%s}\n' % cls)

    def duclass_close(self, node):
        """Close a group of class declarations."""
        for cls in reversed(node['classes']):
            if cls.startswith('language-'):
                language = self.babel.language_name(cls[9:])
                if language:
                    self.out.append('\\end{selectlanguage}\n')
            elif isinstance(node, nodes.table) and cls in Writer.table_style_values:
                pass
            else:
                if not self.fallback_stylesheet:
                    self.fallbacks['DUclass'] = PreambleCmds.duclass
                self.out.append('\\end{DUclass}\n')

    def push_output_collector(self, new_out):
        self.out_stack.append(self.out)
        self.out = new_out

    def pop_output_collector(self):
        self.out = self.out_stack.pop()

    def term_postfix(self, node):
        """
        Return LaTeX code required between term or field name and content.

        In a LaTeX "description" environment (used for definition
        lists and non-docinfo field lists), a ``\\leavevmode``
        between an item's label and content ensures the correct
        placement of certain block constructs.
        """
        for child in node:
            if not isinstance(child, (nodes.Invisible, nodes.footnote,
                                      nodes.citation)):
                break
        else:
            return ''
        if isinstance(child, (nodes.image)):
            return '\\leavevmode\n' # Images get an additional newline.
        if isinstance(child, (nodes.container, nodes.compound)):
            return self.term_postfix(child)
        if not isinstance(child,
                          (nodes.paragraph, nodes.math_block)):
            return r'\leavevmode'
        return ''

    # Visitor methods
    # ---------------

    def visit_Text(self, node):
        self.out.append(self.encode(node.astext()))

    def depart_Text(self, node):
        pass

    def visit_abbreviation(self, node):
        node['classes'].insert(0, 'abbreviation')
        self.visit_inline(node)

    def depart_abbreviation(self, node):
        self.depart_inline(node)

    def visit_acronym(self, node):
        node['classes'].insert(0, 'acronym')
        self.visit_inline(node)

    def depart_acronym(self, node):
        self.depart_inline(node)

    def visit_address(self, node):
        self.visit_docinfo_item(node, 'address')

    def depart_address(self, node):
        self.depart_docinfo_item(node)

    def visit_admonition(self, node):
        # strip the generic 'admonition' from the list of classes
        node['classes'] = [cls for cls in node['classes']
                           if cls != 'admonition']
        if self.settings.legacy_class_functions:
            self.fallbacks['admonition'] = PreambleCmds.admonition_legacy
            if 'error' in node['classes']:
                self.fallbacks['error'] = PreambleCmds.error_legacy
            self.out.append('\n\\DUadmonition[%s]{' % ','.join(node['classes']))
            return
        if not self.fallback_stylesheet:
            self.fallbacks['admonition'] = PreambleCmds.admonition
        if 'error' in node['classes'] and not self.fallback_stylesheet:
            self.fallbacks['error'] = PreambleCmds.error
        self.duclass_open(node)
        self.out.append('\\begin{DUadmonition}')

    def depart_admonition(self, node):
        if self.settings.legacy_class_functions:
            self.out.append('}\n')
            return
        self.out.append('\\end{DUadmonition}\n')
        self.duclass_close(node)

    def visit_author(self, node):
        self.pdfauthor.append(self.attval(node.astext()))
        self.visit_docinfo_item(node, 'author')

    def depart_author(self, node):
        self.depart_docinfo_item(node)

    def visit_authors(self, node):
        # not used: visit_author is called anyway for each author.
        pass

    def depart_authors(self, node):
        pass

    def visit_block_quote(self, node):
        self.duclass_open(node)
        self.out.append('\\begin{quote}')

    def depart_block_quote(self, node):
        self.out.append('\\end{quote}\n')
        self.duclass_close(node)

    def visit_bullet_list(self, node):
        self.duclass_open(node)
        if self.is_toc_list:
            self.out.append('\\begin{list}{}{}')
        else:
            self.out.append('\\begin{itemize}')

    def depart_bullet_list(self, node):
        if self.is_toc_list:
            self.out.append('\\end{list}\n')
        else:
            self.out.append('\\end{itemize}\n')
        self.duclass_close(node)

    def visit_superscript(self, node):
        self.out.append(r'\textsuperscript{')
        if node['classes']:
            self.visit_inline(node)

    def depart_superscript(self, node):
        if node['classes']:
            self.depart_inline(node)
        self.out.append('}')

    def visit_subscript(self, node):
        self.out.append(r'\textsubscript{')
        if node['classes']:
            self.visit_inline(node)

    def depart_subscript(self, node):
        if node['classes']:
            self.depart_inline(node)
        self.out.append('}')

    def visit_caption(self, node):
        self.out.append('\n\\caption{')

    def depart_caption(self, node):
        self.out.append('}\n')

    def visit_title_reference(self, node):
        if not self.fallback_stylesheet:
            self.fallbacks['titlereference'] = PreambleCmds.titlereference
        self.out.append(r'\DUroletitlereference{')
        if node['classes']:
            self.visit_inline(node)

    def depart_title_reference(self, node):
        if node['classes']:
            self.depart_inline(node)
        self.out.append('}')

    def visit_citation(self, node):
        if self._use_latex_citations:
            self.push_output_collector([])
        else:
            ## self.requirements['~fnt_floats'] = PreambleCmds.footnote_floats
            self.out.append(r'\begin{figure}[b]')
            self.append_hypertargets(node)

    def depart_citation(self, node):
        if self._use_latex_citations:
            # TODO: normalize label
            label = self.out[0]
            text = ''.join(self.out[1:])
            self._bibitems.append([label, text])
            self.pop_output_collector()
        else:
            self.out.append('\\end{figure}\n')

    def visit_citation_reference(self, node):
        if self._use_latex_citations:
            if not self.inside_citation_reference_label:
                self.out.append(r'\cite{')
                self.inside_citation_reference_label = 1
            else:
                assert self.out[-1] in (' ', '\n'),\
                        'unexpected non-whitespace while in reference label'
                del self.out[-1]
        else:
            href = ''
            if 'refid' in node:
                href = node['refid']
            elif 'refname' in node:
                href = self.document.nameids[node['refname']]
            self.out.append('\\hyperlink{%s}{[' % href)

    def depart_citation_reference(self, node):
        # TODO: normalize labels
        if self._use_latex_citations:
            followup_citation = False
            # check for a following citation separated by a space or newline
            sibling = node.next_node(descend=False, siblings=True)
            if (isinstance(sibling, nodes.Text)
                and sibling.astext() in (' ', '\n')):
                sibling2 = sibling.next_node(descend=False, siblings=True)
                if isinstance(sibling2, nodes.citation_reference):
                        followup_citation = True
            if followup_citation:
                self.out.append(',')
            else:
                self.out.append('}')
                self.inside_citation_reference_label = False
        else:
            self.out.append(']}')

    def visit_classifier(self, node):
        self.out.append('(\\textbf{')

    def depart_classifier(self, node):
        self.out.append('})')

    def visit_colspec(self, node):
        self.active_table.visit_colspec(node)

    def depart_colspec(self, node):
        pass

    def visit_comment(self, node):
        if not isinstance(node.parent, nodes.compound):
             self.out.append('\n')
        # Precede every line with a comment sign, wrap in newlines
        self.out.append('%% %s\n' % node.astext().replace('\n', '\n% '))
        raise nodes.SkipNode

    def depart_comment(self, node):
        pass

    def visit_compound(self, node):
        if isinstance(node.parent, nodes.compound):
            self.out.append('\n')
        node['classes'].insert(0, 'compound')
        self.duclass_open(node)

    def depart_compound(self, node):
        self.duclass_close(node)

    def visit_contact(self, node):
        self.visit_docinfo_item(node, 'contact')

    def depart_contact(self, node):
        self.depart_docinfo_item(node)

    def visit_container(self, node):
        self.duclass_open(node)

    def depart_container(self, node):
        self.duclass_close(node)

    def visit_copyright(self, node):
        self.visit_docinfo_item(node, 'copyright')

    def depart_copyright(self, node):
        self.depart_docinfo_item(node)

    def visit_date(self, node):
        self.visit_docinfo_item(node, 'date')

    def depart_date(self, node):
        self.depart_docinfo_item(node)

    def visit_decoration(self, node):
        # header and footer
        pass

    def depart_decoration(self, node):
        pass

    def visit_definition(self, node):
        pass

    def depart_definition(self, node):
        self.out.append('\n')                # TODO: just pass?

    def visit_definition_list(self, node):
        self.duclass_open(node)
        self.out.append('\\begin{description}\n')

    def depart_definition_list(self, node):
        self.out.append('\\end{description}\n')
        self.duclass_close(node)

    def visit_definition_list_item(self, node):
        pass

    def depart_definition_list_item(self, node):
        pass

    def visit_description(self, node):
        self.out.append(' ')

    def depart_description(self, node):
        pass

    def visit_docinfo(self, node):
        self.push_output_collector(self.docinfo)

    def depart_docinfo(self, node):
        self.pop_output_collector()
        # Some itmes (e.g. author) end up at other places
        if self.docinfo:
            # tabularx: automatic width of columns, no page breaks allowed.
            self.requirements['tabularx'] = r'\usepackage{tabularx}'
            if not self.fallback_stylesheet:
                self.fallbacks['_providelength'] = PreambleCmds.providelength
                self.fallbacks['docinfo'] = PreambleCmds.docinfo
            #
            self.docinfo.insert(0, '\n% Docinfo\n'
                                '\\begin{center}\n'
                                '\\begin{tabularx}{\\DUdocinfowidth}{lX}\n')
            self.docinfo.append('\\end{tabularx}\n'
                                '\\end{center}\n')

    def visit_docinfo_item(self, node, name):
        if self.use_latex_docinfo:
            if name in ('author', 'organization', 'contact', 'address'):
                # We attach these to the last author.  If any of them precedes
                # the first author, put them in a separate "author" group
                # (in lack of better semantics).
                if name == 'author' or not self.author_stack:
                    self.author_stack.append([])
                if name == 'address':   # newlines are meaningful
                    self.insert_newline = True
                    text = self.encode(node.astext())
                    self.insert_newline = False
                else:
                    text = self.attval(node.astext())
                self.author_stack[-1].append(text)
                raise nodes.SkipNode
            elif name == 'date':
                self.date.append(self.attval(node.astext()))
                raise nodes.SkipNode
        self.out.append('\\textbf{%s}: &\n\t' % self.language_label(name))
        if name == 'address':
            self.insert_newline = True
            self.out.append('{\\raggedright\n')
            self.context.append(' } \\\\\n')
        else:
            self.context.append(' \\\\\n')

    def depart_docinfo_item(self, node):
        self.out.append(self.context.pop())
        # for address we did set insert_newline
        self.insert_newline = False

    def visit_doctest_block(self, node):
        self.visit_literal_block(node)

    def depart_doctest_block(self, node):
        self.depart_literal_block(node)

    def visit_document(self, node):
        # titled document?
        if (self.use_latex_docinfo or len(node) and
            isinstance(node[0], nodes.title)):
            protect = (self.settings.documentclass == 'memoir')
            self.title_labels += self.ids_to_labels(node, set_anchor=False,
                                                    protect=protect)

    def depart_document(self, node):
        # Complete header with information gained from walkabout
        # * language setup
        if (self.babel.otherlanguages or
            self.babel.language not in ('', 'english')):
            self.requirements['babel'] = self.babel()
        # * conditional requirements (before style sheet)
        self.requirements = self.requirements.sortedvalues()
        # * coditional fallback definitions (after style sheet)
        self.fallbacks = self.fallbacks.sortedvalues()
        # * PDF properties
        self.pdfsetup.append(PreambleCmds.linking % self.hyperref_options)
        if self.pdfauthor:
            authors = self.author_separator.join(self.pdfauthor)
            self.pdfinfo.append('  pdfauthor={%s}' % authors)
        if self.pdfinfo:
            self.pdfsetup += [r'\hypersetup{'] + self.pdfinfo + ['}']
        # Complete body
        # * document title (with "use_latex_docinfo" also
        #   'author', 'organization', 'contact', 'address' and 'date')
        if self.title or (
           self.use_latex_docinfo and (self.author_stack or self.date)):
            # \title (empty \title prevents error with \maketitle)
            title = [''.join(self.title)]
            if self.title:
                title += self.title_labels
            if self.subtitle:
                title += [r'\\',
                          r'\DUdocumentsubtitle{%s}' % ''.join(self.subtitle)
                         ] + self.subtitle_labels
            self.titledata.append(r'\title{%s}' % '%\n  '.join(title))
            # \author (empty \author prevents warning with \maketitle)
            authors = ['\\\\\n'.join(author_entry)
                        for author_entry in self.author_stack]
            self.titledata.append(r'\author{%s}' %
                                      ' \\and\n'.join(authors))
            # \date (empty \date prevents defaulting to \today)
            self.titledata.append(r'\date{%s}' % ', '.join(self.date))
            # \maketitle in the body formats title with LaTeX
            self.body_pre_docinfo.append('\\maketitle\n')

        # * bibliography
        #   TODO insertion point of bibliography should be configurable.
        if self._use_latex_citations and len(self._bibitems)>0:
            if not self.bibtex:
                widest_label = ''
                for bi in self._bibitems:
                    if len(widest_label)<len(bi[0]):
                        widest_label = bi[0]
                self.out.append('\n\\begin{thebibliography}{%s}\n' %
                                 widest_label)
                for bi in self._bibitems:
                    # cite_key: underscores must not be escaped
                    cite_key = bi[0].replace(r'\_', '_')
                    self.out.append('\\bibitem[%s]{%s}{%s}\n' %
                                     (bi[0], cite_key, bi[1]))
                self.out.append('\\end{thebibliography}\n')
            else:
                self.out.append('\n\\bibliographystyle{%s}\n' %
                                self.bibtex[0])
                self.out.append('\\bibliography{%s}\n' % self.bibtex[1])
        # * make sure to generate a toc file if needed for local contents:
        if 'minitoc' in self.requirements and not self.has_latex_toc:
            self.out.append('\n\\faketableofcontents % for local ToCs\n')

    def visit_emphasis(self, node):
        self.out.append('\\emph{')
        if node['classes']:
            self.visit_inline(node)

    def depart_emphasis(self, node):
        if node['classes']:
            self.depart_inline(node)
        self.out.append('}')

    # Append column delimiters and advance column counter,
    # if the current cell is a multi-row continuation."""
    def insert_additional_table_colum_delimiters(self):
        while self.active_table.get_rowspan(
                                self.active_table.get_entry_number()):
            self.out.append(' & ')
            self.active_table.visit_entry() # increment cell count

    def visit_entry(self, node):
        # cell separation
        if self.active_table.get_entry_number() == 0:
            self.insert_additional_table_colum_delimiters()
        else:
            self.out.append(' & ')

        # multirow, multicolumn
        if 'morerows' in node and 'morecols' in node:
            raise NotImplementedError('Cells that '
            'span multiple rows *and* columns currently not supported, sorry.')
            # TODO: should be possible with LaTeX, see e.g.
            # http://texblog.org/2012/12/21/multi-column-and-multi-row-cells-in-latex-tables/
        # multirow in LaTeX simply will enlarge the cell over several rows
        # (the following n if n is positive, the former if negative).
        if 'morerows' in node:
            self.requirements['multirow'] = r'\usepackage{multirow}'
            mrows = node['morerows'] + 1
            self.active_table.set_rowspan(
                            self.active_table.get_entry_number(), mrows)
            self.out.append('\\multirow{%d}{%s}{' %
                            (mrows, self.active_table.get_column_width()))
            self.context.append('}')
        elif 'morecols' in node:
            # the vertical bar before column is missing if it is the first
            # column. the one after always.
            if self.active_table.get_entry_number() == 0:
                bar1 = self.active_table.get_vertical_bar()
            else:
                bar1 = ''
            mcols = node['morecols'] + 1
            self.out.append('\\multicolumn{%d}{%s%s%s}{' %
                    (mcols, bar1,
                     self.active_table.get_multicolumn_width(
                        self.active_table.get_entry_number(),
                        mcols),
                     self.active_table.get_vertical_bar()))
            self.context.append('}')
        else:
            self.context.append('')

        # bold header/stub-column
        if len(node) and (isinstance(node.parent.parent, nodes.thead)
                          or self.active_table.is_stub_column()):
            self.out.append('\\textbf{')
            self.context.append('}')
        else:
            self.context.append('')

        # if line ends with '{', mask line break to prevent spurious whitespace
        if (not self.active_table.colwidths_auto
            and self.out[-1].endswith("{")
            and node.astext()):
                self.out.append("%")

        self.active_table.visit_entry() # increment cell count

    def depart_entry(self, node):
        self.out.append(self.context.pop()) # header / not header
        self.out.append(self.context.pop()) # multirow/column
        # insert extra "&"s, if following rows are spanned from above:
        self.insert_additional_table_colum_delimiters()

    def visit_row(self, node):
        self.active_table.visit_row()

    def depart_row(self, node):
        self.out.extend(self.active_table.depart_row())

    def visit_enumerated_list(self, node):
        # enumeration styles:
        types = {'': '',
                  'arabic':'arabic',
                  'loweralpha':'alph',
                  'upperalpha':'Alph',
                  'lowerroman':'roman',
                  'upperroman':'Roman'}
        # the 4 default LaTeX enumeration labels: präfix, enumtype, suffix,
        labels = [('',  'arabic', '.'), #  1.
                  ('(', 'alph',   ')'), # (a)
                  ('',  'roman',  '.'), #  i.
                  ('',  'Alph',   '.')] #  A.

        prefix = ''
        if self.compound_enumerators:
            if (self.section_prefix_for_enumerators and self.section_level
                and not self._enumeration_counters):
                prefix = '.'.join([str(n) for n in
                                   self._section_number[:self.section_level]]
                                 ) + self.section_enumerator_separator
            if self._enumeration_counters:
                prefix += self._enumeration_counters[-1]
        # TODO: use LaTeX default for unspecified label-type?
        #       (needs change of parser)
        prefix += node.get('prefix', '')
        enumtype = types[node.get('enumtype' '')]
        suffix = node.get('suffix', '')

        enumeration_level = len(self._enumeration_counters)+1
        counter_name = 'enum' + roman.toRoman(enumeration_level).lower()
        label = r'%s\%s{%s}%s' % (prefix, enumtype, counter_name, suffix)
        self._enumeration_counters.append(label)

        self.duclass_open(node)
        if enumeration_level <= 4:
            self.out.append('\\begin{enumerate}')
            if (prefix, enumtype, suffix
               ) != labels[enumeration_level-1]:
                self.out.append('\n\\renewcommand{\\label%s}{%s}' %
                                (counter_name, label))
        else:
            self.fallbacks[counter_name] = '\\newcounter{%s}' % counter_name
            self.out.append('\\begin{list}')
            self.out.append('{%s}' % label)
            self.out.append('{\\usecounter{%s}}' % counter_name)
        if 'start' in node:
            self.out.append('\n\\setcounter{%s}{%d}' %
                            (counter_name, node['start']-1))


    def depart_enumerated_list(self, node):
        if len(self._enumeration_counters) <= 4:
            self.out.append('\\end{enumerate}\n')
        else:
            self.out.append('\\end{list}\n')
        self.duclass_close(node)
        self._enumeration_counters.pop()

    def visit_field(self, node):
        # output is done in field_body, field_name
        pass

    def depart_field(self, node):
        pass

    def visit_field_body(self, node):
        if not isinstance(node.parent.parent, nodes.docinfo):
            self.out.append(self.term_postfix(node))

    def depart_field_body(self, node):
        if self.out is self.docinfo:
            self.out.append(r'\\'+'\n')

    def visit_field_list(self, node):
        self.duclass_open(node)
        if self.out is not self.docinfo:
            if not self.fallback_stylesheet:
                self.fallbacks['fieldlist'] = PreambleCmds.fieldlist
            self.out.append('\\begin{DUfieldlist}')

    def depart_field_list(self, node):
        if self.out is not self.docinfo:
            self.out.append('\\end{DUfieldlist}\n')
        self.duclass_close(node)

    def visit_field_name(self, node):
        if self.out is self.docinfo:
            self.out.append('\\textbf{')
        else:
            # Commands with optional args inside an optional arg must be put
            # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
            self.out.append('\n\\item[{')

    def depart_field_name(self, node):
        if self.out is self.docinfo:
            self.out.append('}: &')
        else:
            self.out.append(':}]')

    def visit_figure(self, node):
        self.requirements['float'] = PreambleCmds.float
        self.duclass_open(node)
        # The 'align' attribute sets the "outer alignment",
        # for "inner alignment" use LaTeX default alignment (similar to HTML)
        alignment = node.attributes.get('align', 'center')
        if alignment != 'center':
            # The LaTeX "figure" environment always uses the full linewidth,
            # so "outer alignment" is ignored. Just write a comment.
            # TODO: use the wrapfigure environment?
            self.out.append('\\begin{figure} %% align = "%s"\n' % alignment)
        else:
            self.out.append('\\begin{figure}\n')
        if node.get('ids'):
            self.out += self.ids_to_labels(node) + ['\n']

    def depart_figure(self, node):
        self.out.append('\\end{figure}\n')
        self.duclass_close(node)

    def visit_footer(self, node):
        self.push_output_collector([])
        self.out.append(r'\newcommand{\DUfooter}{')

    def depart_footer(self, node):
        self.out.append('}')
        self.requirements['~footer'] = ''.join(self.out)
        self.pop_output_collector()

    def visit_footnote(self, node):
        try:
            backref = node['backrefs'][0]
        except IndexError:
            backref = node['ids'][0] # no backref, use self-ref instead
        if self.docutils_footnotes:
            if not self.fallback_stylesheet:
                self.fallbacks['footnotes'] = PreambleCmds.footnotes
            num = node[0].astext()
            if self.settings.footnote_references == 'brackets':
                num = '[%s]' % num
            self.out.append('%%\n\\DUfootnotetext{%s}{%s}{%s}{' %
                            (node['ids'][0], backref, self.encode(num)))
            if node['ids'] == node['names']:
                self.out += self.ids_to_labels(node)
            # mask newline to prevent spurious whitespace if paragraph follows:
            if node[1:] and isinstance(node[1], nodes.paragraph):
                self.out.append('%')
        # TODO: "real" LaTeX \footnote{}s (see visit_footnotes_reference())

    def depart_footnote(self, node):
        self.out.append('}\n')

    def visit_footnote_reference(self, node):
        href = ''
        if 'refid' in node:
            href = node['refid']
        elif 'refname' in node:
            href = self.document.nameids[node['refname']]
        # if not self.docutils_footnotes:
            # TODO: insert footnote content at (or near) this place
            # print("footnote-ref to", node['refid'])
            # footnotes = (self.document.footnotes +
            #              self.document.autofootnotes +
            #              self.document.symbol_footnotes)
            # for footnote in footnotes:
            #     # print(footnote['ids'])
            #     if node.get('refid', '') in footnote['ids']:
            #         print('matches', footnote['ids'])
        format = self.settings.footnote_references
        if format == 'brackets':
            self.append_hypertargets(node)
            self.out.append('\\hyperlink{%s}{[' % href)
            self.context.append(']}')
        else:
            if not self.fallback_stylesheet:
                self.fallbacks['footnotes'] = PreambleCmds.footnotes
            self.out.append(r'\DUfootnotemark{%s}{%s}{' %
                            (node['ids'][0], href))
            self.context.append('}')

    def depart_footnote_reference(self, node):
        self.out.append(self.context.pop())

    # footnote/citation label
    def label_delim(self, node, bracket, superscript):
        if isinstance(node.parent, nodes.footnote):
            raise nodes.SkipNode
        else:
            assert isinstance(node.parent, nodes.citation)
            if not self._use_latex_citations:
                self.out.append(bracket)

    def visit_label(self, node):
        """footnote or citation label: in brackets or as superscript"""
        self.label_delim(node, '[', '\\textsuperscript{')

    def depart_label(self, node):
        self.label_delim(node, ']', '}')

    # elements generated by the framework e.g. section numbers.
    def visit_generated(self, node):
        pass

    def depart_generated(self, node):
        pass

    def visit_header(self, node):
        self.push_output_collector([])
        self.out.append(r'\newcommand{\DUheader}{')

    def depart_header(self, node):
        self.out.append('}')
        self.requirements['~header'] = ''.join(self.out)
        self.pop_output_collector()

    def to_latex_length(self, length_str, pxunit=None):
        """Convert `length_str` with rst lenght to LaTeX length
        """
        if pxunit is not None:
            sys.stderr.write('deprecation warning: LaTeXTranslator.to_latex_length()'
                             ' option `pxunit` will be removed.')
        match = re.match(r'(\d*\.?\d*)\s*(\S*)', length_str)
        if not match:
            return length_str
        value, unit = match.groups()[:2]
        # no unit or "DTP" points (called 'bp' in TeX):
        if unit in ('', 'pt'):
            length_str = '%sbp' % value
        # percentage: relate to current line width
        elif unit == '%':
            length_str = '%.3f\\linewidth' % (float(value)/100.0)
        elif self.is_xetex and unit == 'px':
            # XeTeX does not know the length unit px.
            # Use \pdfpxdimen, the macro to set the value of 1 px in pdftex.
            # This way, configuring works the same for pdftex and xetex.
            if not self.fallback_stylesheet:
                self.fallbacks['_providelength'] = PreambleCmds.providelength
            self.fallbacks['px'] = '\n\\DUprovidelength{\\pdfpxdimen}{1bp}\n'
            length_str = r'%s\pdfpxdimen' % value
        return length_str

    def visit_image(self, node):
        self.requirements['graphicx'] = self.graphicx_package
        attrs = node.attributes
        # Convert image URI to a local file path
        imagepath = url2pathname(attrs['uri']).replace('\\', '/')
        # alignment defaults:
        if not 'align' in attrs:
            # Set default align of image in a figure to 'center'
            if isinstance(node.parent, nodes.figure):
                attrs['align'] = 'center'
            self.set_align_from_classes(node)
        # pre- and postfix (prefix inserted in reverse order)
        pre = []
        post = []
        include_graphics_options = []
        align_codes = {
            # inline images: by default latex aligns the bottom.
            'bottom': ('', ''),
            'middle': (r'\raisebox{-0.5\height}{', '}'),
            'top':    (r'\raisebox{-\height}{', '}'),
            # block level images:
            'center': (r'\noindent\makebox[\linewidth][c]{', '}'),
            'left':   (r'\noindent{', r'\hfill}'),
            'right':  (r'\noindent{\hfill', '}'),}
        if 'align' in attrs:
            # TODO: warn or ignore non-applicable alignment settings?
            try:
                align_code = align_codes[attrs['align']]
                pre.append(align_code[0])
                post.append(align_code[1])
            except KeyError:
                pass                    # TODO: warn?
        if 'height' in attrs:
            include_graphics_options.append('height=%s' %
                            self.to_latex_length(attrs['height']))
        if 'scale' in attrs:
            include_graphics_options.append('scale=%f' %
                                            (attrs['scale'] / 100.0))
        if 'width' in attrs:
            include_graphics_options.append('width=%s' %
                            self.to_latex_length(attrs['width']))
        if not (self.is_inline(node) or
                isinstance(node.parent, (nodes.figure, nodes.compound))):
            pre.append('\n')
        if not (self.is_inline(node) or
                isinstance(node.parent, nodes.figure)):
            post.append('\n')
        pre.reverse()
        self.out.extend(pre)
        options = ''
        if include_graphics_options:
            options = '[%s]' % (','.join(include_graphics_options))
        self.out.append('\\includegraphics%s{%s}' % (options, imagepath))
        self.out.extend(post)

    def depart_image(self, node):
        if node.get('ids'):
            self.out += self.ids_to_labels(node) + ['\n']

    def visit_inline(self, node): # <span>, i.e. custom roles
        for cls in node['classes']:
            if cls.startswith('language-'):
                language = self.babel.language_name(cls[9:])
                if language:
                    self.babel.otherlanguages[language] = True
                    self.out.append(r'\foreignlanguage{%s}{' % language)
            else:
                if not self.fallback_stylesheet:
                    self.fallbacks['inline'] = PreambleCmds.inline
                self.out.append(r'\DUrole{%s}{' % cls)

    def depart_inline(self, node):
        self.out.append('}' * len(node['classes']))

    def visit_legend(self, node):
        if not self.fallback_stylesheet:
            self.fallbacks['legend'] = PreambleCmds.legend
        self.out.append('\\begin{DUlegend}')

    def depart_legend(self, node):
        self.out.append('\\end{DUlegend}\n')

    def visit_line(self, node):
        self.out.append(r'\item[] ')

    def depart_line(self, node):
        self.out.append('\n')

    def visit_line_block(self, node):
        if not self.fallback_stylesheet:
            self.fallbacks['_providelength'] = PreambleCmds.providelength
            self.fallbacks['lineblock'] = PreambleCmds.lineblock
        self.set_align_from_classes(node)
        if isinstance(node.parent, nodes.line_block):
            self.out.append('\\item[]\n'
                             '\\begin{DUlineblock}{\\DUlineblockindent}\n')
            # nested line-blocks cannot be given class arguments
        else:
            self.duclass_open(node)
            self.out.append('\\begin{DUlineblock}{0em}\n')
            self.insert_align_declaration(node)

    def depart_line_block(self, node):
        self.out.append('\\end{DUlineblock}\n')
        self.duclass_close(node)

    def visit_list_item(self, node):
        self.out.append('\n\\item ')

    def depart_list_item(self, node):
        pass

    def visit_literal(self, node):
        self.literal = True
        if ('code' in node['classes'] and
            self.settings.syntax_highlight != 'none'):
            self.requirements['color'] = PreambleCmds.color
            if not self.fallback_stylesheet:
                self.fallbacks['code'] = PreambleCmds.highlight_rules
        self.out.append('\\texttt{')
        if node['classes']:
            self.visit_inline(node)

    def depart_literal(self, node):
        self.literal = False
        if node['classes']:
            self.depart_inline(node)
        self.out.append('}')

    # Literal blocks are used for '::'-prefixed literal-indented
    # blocks of text, where the inline markup is not recognized,
    # but are also the product of the "parsed-literal" directive,
    # where the markup is respected.
    #
    # In both cases, we want to use a typewriter/monospaced typeface.
    # For "real" literal-blocks, we can use \verbatim, while for all
    # the others we must use \ttfamily and \raggedright.
    #
    # We can distinguish between the two kinds by the number of
    # siblings that compose this node: if it is composed by a
    # single element, it's either
    # * a real one,
    # * a parsed-literal that does not contain any markup, or
    # * a parsed-literal containing just one markup construct.
    def is_plaintext(self, node):
        """Check whether a node can be typeset verbatim"""
        return (len(node) == 1) and isinstance(node[0], nodes.Text)

    def visit_literal_block(self, node):
        """Render a literal block.

        Corresponding rST elements: literal block, parsed-literal, code.
        """
        packages = {'lstlisting':  r'\usepackage{listings}' '\n'
                                   r'\lstset{xleftmargin=\leftmargin}',
                    'listing': r'\usepackage{moreverb}',
                    'Verbatim': r'\usepackage{fancyvrb}',
                    'verbatimtab': r'\usepackage{moreverb}'}

        literal_env = self.literal_block_env

        # Check, if it is possible to use a literal-block environment
        _plaintext = self.is_plaintext(node)
        _in_table = self.active_table.is_open()
        # TODO: fails if normal text precedes the literal block.
        #       Check parent node instead?
        _autowidth_table = _in_table and self.active_table.colwidths_auto
        _use_env = _plaintext and not isinstance(node.parent,
                    (nodes.footnote, nodes.admonition, nodes.system_message))
        _use_listings = (literal_env == 'lstlisting') and _use_env

        # Labels and classes:
        if node.get('ids'):
            self.out += ['\n'] + self.ids_to_labels(node)
        self.duclass_open(node)
        # Highlight code?
        if (not _plaintext
            and 'code' in node['classes']
            and self.settings.syntax_highlight != 'none'):
            self.requirements['color'] = PreambleCmds.color
            if not self.fallback_stylesheet:
                self.fallbacks['code'] = PreambleCmds.highlight_rules
        # Wrap?
        if _in_table and _use_env and not _autowidth_table:
            # Wrap in minipage to prevent extra vertical space
            # with alltt and verbatim-like environments:
            self.fallbacks['ttem'] = '\n'.join(['',
                r'% character width in monospaced font',
                r'\newlength{\ttemwidth}',
                r'\settowidth{\ttemwidth}{\ttfamily M}'])
            self.out.append('\\begin{minipage}{%d\\ttemwidth}\n' %
                (max(len(line) for line in node.astext().split('\n'))))
            self.context.append('\n\\end{minipage}\n')
        elif not _in_table and not _use_listings:
            # Wrap in quote to set off vertically and indent
            self.out.append('\\begin{quote}\n')
            self.context.append('\n\\end{quote}\n')
        else:
            self.context.append('\n')

        # Use verbatim-like environment, if defined and possible
        # (in an auto-width table, only listings works):
        if literal_env and _use_env and (not _autowidth_table
                                         or _use_listings):
            try:
                self.requirements['literal_block'] = packages[literal_env]
            except KeyError:
                pass
            self.verbatim = True
            if _in_table and _use_listings:
                self.out.append('\\lstset{xleftmargin=0pt}\n')
            self.out.append('\\begin{%s}%s\n' %
                            (literal_env, self.literal_block_options))
            self.context.append('\n\\end{%s}' % literal_env)
        elif _use_env and not _autowidth_table:
            self.alltt = True
            self.requirements['alltt'] = r'\usepackage{alltt}'
            self.out.append('\\begin{alltt}\n')
            self.context.append('\n\\end{alltt}')
        else:
            self.literal = True
            self.insert_newline = True
            self.insert_non_breaking_blanks = True
            # \raggedright ensures leading blanks are respected but
            # leads to additional leading vspace if the first line
            # of the block is overfull :-(
            self.out.append('\\ttfamily\\raggedright\n')
            self.context.append('')

    def depart_literal_block(self, node):
        self.insert_non_breaking_blanks = False
        self.insert_newline = False
        self.literal = False
        self.verbatim = False
        self.alltt = False
        self.out.append(self.context.pop())
        self.out.append(self.context.pop())
        self.duclass_close(node)

    def visit_meta(self, node):
        name = node.attributes.get('name')
        content = node.attributes.get('content')
        if not name or not content:
            return
        if name in ('author', 'creator', 'keywords', 'subject', 'title'):
            # fields with dedicated hyperref options:
            self.pdfinfo.append('  pdf%s={%s},'%(name, content))
        elif name == 'producer':
            self.pdfinfo.append('  addtopdfproducer={%s},'%content)
        else:
            # generic interface (case sensitive!)
            self.pdfinfo.append('  pdfinfo={%s={%s}},'%(name, content))

    def depart_meta(self, node):
        pass

    def visit_math(self, node, math_env='$'):
        """math role"""
        if node['classes']:
            self.visit_inline(node)
        self.requirements['amsmath'] = r'\usepackage{amsmath}'
        math_code = node.astext().translate(unichar2tex.uni2tex_table)
        if node.get('ids'):
            math_code = '\n'.join([math_code] + self.ids_to_labels(node))
        if math_env == '$':
            if self.alltt:
                wrapper = u'\\(%s\\)'
            else:
                wrapper = u'$%s$'
        else:
            wrapper = u'\n'.join(['%%',
                                 r'\begin{%s}' % math_env,
                                 '%s',
                                 r'\end{%s}' % math_env])
        self.out.append(wrapper % math_code)
        if node['classes']:
            self.depart_inline(node)
        # Content already processed:
        raise nodes.SkipNode

    def depart_math(self, node):
        pass # never reached

    def visit_math_block(self, node):
        math_env = pick_math_environment(node.astext())
        self.visit_math(node, math_env=math_env)

    def depart_math_block(self, node):
        pass # never reached

    def visit_option(self, node):
        if self.context[-1]:
            # this is not the first option
            self.out.append(', ')

    def depart_option(self, node):
        # flag that the first option is done.
        self.context[-1] += 1

    def visit_option_argument(self, node):
        """Append the delimiter betweeen an option and its argument to body."""
        self.out.append(node.get('delimiter', ' '))

    def depart_option_argument(self, node):
        pass

    def visit_option_group(self, node):
        self.out.append('\n\\item[')
        # flag for first option
        self.context.append(0)

    def depart_option_group(self, node):
        self.context.pop() # the flag
        self.out.append('] ')

    def visit_option_list(self, node):
        if not self.fallback_stylesheet:
            self.fallbacks['_providelength'] = PreambleCmds.providelength
            self.fallbacks['optionlist'] = PreambleCmds.optionlist
        self.duclass_open(node)
        self.out.append('\\begin{DUoptionlist}')

    def depart_option_list(self, node):
        self.out.append('\\end{DUoptionlist}\n')
        self.duclass_close(node)

    def visit_option_list_item(self, node):
        pass

    def depart_option_list_item(self, node):
        pass

    def visit_option_string(self, node):
        ##self.out.append(self.starttag(node, 'span', '', CLASS='option'))
        pass

    def depart_option_string(self, node):
        ##self.out.append('</span>')
        pass

    def visit_organization(self, node):
        self.visit_docinfo_item(node, 'organization')

    def depart_organization(self, node):
        self.depart_docinfo_item(node)

    def visit_paragraph(self, node):
        # insert blank line, unless
        # * the paragraph is first in a list item, compound, or container
        # * follows a non-paragraph node in a compound,
        # * is in a table with auto-width columns
        index = node.parent.index(node)
        if index == 0 and isinstance(node.parent,
                (nodes.list_item, nodes.description,
                 nodes.compound, nodes.container)):
            pass
        elif (index > 0
              and isinstance(node.parent, nodes.compound)
              and not isinstance(node.parent[index - 1],
                                 (nodes.paragraph, nodes.compound))):
            pass
        elif self.active_table.colwidths_auto:
            if index == 1: # second paragraph
                self.warn('LaTeX merges paragraphs in tables '
                          'with auto-sized columns!', base_node=node)
            if index > 0:
                self.out.append('\n')
        else:
            self.out.append('\n')
        if node.get('ids'):
            self.out += self.ids_to_labels(node) + ['\n']
        if node['classes']:
            self.visit_inline(node)

    def depart_paragraph(self, node):
        if node['classes']:
            self.depart_inline(node)
        if not self.active_table.colwidths_auto:
            self.out.append('\n')

    def visit_problematic(self, node):
        self.requirements['color'] = PreambleCmds.color
        self.out.append('%\n')
        self.append_hypertargets(node)
        self.out.append(r'\hyperlink{%s}{\textbf{\color{red}' % node['refid'])

    def depart_problematic(self, node):
        self.out.append('}}')

    def visit_raw(self, node):
        if not 'latex' in node.get('format', '').split():
            raise nodes.SkipNode
        if not self.is_inline(node):
            self.out.append('\n')
        if node['classes']:
            self.visit_inline(node)
        # append "as-is" skipping any LaTeX-encoding
        self.verbatim = True

    def depart_raw(self, node):
        self.verbatim = False
        if node['classes']:
            self.depart_inline(node)
        if not self.is_inline(node):
            self.out.append('\n')

    def has_unbalanced_braces(self, string):
        """Test whether there are unmatched '{' or '}' characters."""
        level = 0
        for ch in string:
            if ch == '{':
                level += 1
            if ch == '}':
                level -= 1
            if level < 0:
                return True
        return level != 0

    def visit_reference(self, node):
        # We need to escape #, \, and % if we use the URL in a command.
        special_chars = {ord('#'): u'\\#',
                         ord('%'): u'\\%',
                         ord('\\'): u'\\\\',
                        }
        # external reference (URL)
        if 'refuri' in node:
            href = unicode(node['refuri']).translate(special_chars)
            # problematic chars double caret and unbalanced braces:
            if href.find('^^') != -1 or self.has_unbalanced_braces(href):
                self.error(
                    'External link "%s" not supported by LaTeX.\n'
                    ' (Must not contain "^^" or unbalanced braces.)' % href)
            if node['refuri'] == node.astext():
                self.out.append(r'\url{%s}' % href)
                raise nodes.SkipNode
            self.out.append(r'\href{%s}{' % href)
            return
        # internal reference
        if 'refid' in node:
            href = node['refid']
        elif 'refname' in node:
            href = self.document.nameids[node['refname']]
        else:
            raise AssertionError('Unknown reference.')
        if not self.is_inline(node):
            self.out.append('\n')
        self.out.append('\\hyperref[%s]{' % href)
        if self._reference_label:
            self.out.append('\\%s{%s}}' %
                            (self._reference_label, href.replace('#', '')))
            raise nodes.SkipNode

    def depart_reference(self, node):
        self.out.append('}')
        if not self.is_inline(node):
            self.out.append('\n')

    def visit_revision(self, node):
        self.visit_docinfo_item(node, 'revision')

    def depart_revision(self, node):
        self.depart_docinfo_item(node)

    def visit_rubric(self, node):
        if not self.fallback_stylesheet:
            self.fallbacks['rubric'] = PreambleCmds.rubric
        # class wrapper would interfere with ``\section*"`` type commands
        # (spacing/indent of first paragraph)
        self.out.append('\n\\DUrubric{')

    def depart_rubric(self, node):
        self.out.append('}\n')

    def visit_section(self, node):
        self.section_level += 1
        # Initialize counter for potential subsections:
        self._section_number.append(0)
        # Counter for this section's level (initialized by parent section):
        self._section_number[self.section_level - 1] += 1

    def depart_section(self, node):
        # Remove counter for potential subsections:
        self._section_number.pop()
        self.section_level -= 1

    def visit_sidebar(self, node):
        self.duclass_open(node)
        self.requirements['color'] = PreambleCmds.color
        if not self.fallback_stylesheet:
            self.fallbacks['sidebar'] = PreambleCmds.sidebar
        self.out.append('\\DUsidebar{')

    def depart_sidebar(self, node):
        self.out.append('}\n')
        self.duclass_close(node)

    attribution_formats = {'dash': (u'—', ''), # EM DASH
                           'parentheses': ('(', ')'),
                           'parens': ('(', ')'),
                           'none': ('', '')}

    def visit_attribution(self, node):
        prefix, suffix = self.attribution_formats[self.settings.attribution]
        self.out.append('\\nopagebreak\n\n\\raggedleft ')
        self.out.append(prefix)
        self.context.append(suffix)

    def depart_attribution(self, node):
        self.out.append(self.context.pop() + '\n')

    def visit_status(self, node):
        self.visit_docinfo_item(node, 'status')

    def depart_status(self, node):
        self.depart_docinfo_item(node)

    def visit_strong(self, node):
        self.out.append('\\textbf{')
        if node['classes']:
            self.visit_inline(node)

    def depart_strong(self, node):
        if node['classes']:
            self.depart_inline(node)
        self.out.append('}')

    def visit_substitution_definition(self, node):
        raise nodes.SkipNode

    def visit_substitution_reference(self, node):
        self.unimplemented_visit(node)

    def visit_subtitle(self, node):
        if isinstance(node.parent, nodes.document):
            self.push_output_collector(self.subtitle)
            if not self.fallback_stylesheet:
                self.fallbacks['documentsubtitle'] = PreambleCmds.documentsubtitle
            protect = (self.settings.documentclass == 'memoir')
            self.subtitle_labels += self.ids_to_labels(node, set_anchor=False,
                                                       protect=protect)
        # section subtitle: "starred" (no number, not in ToC)
        elif isinstance(node.parent, nodes.section):
            self.out.append(r'\%s*{' %
                             self.d_class.section(self.section_level + 1))
        else:
            if not self.fallback_stylesheet:
                self.fallbacks['subtitle'] = PreambleCmds.subtitle
            self.out.append('\n\\DUsubtitle{')

    def depart_subtitle(self, node):
        if isinstance(node.parent, nodes.document):
            self.pop_output_collector()
        else:
            self.out.append('}\n')

    def visit_system_message(self, node):
        self.requirements['color'] = PreambleCmds.color
        if not self.fallback_stylesheet:
            self.fallbacks['title'] = PreambleCmds.title
        if self.settings.legacy_class_functions:
            self.fallbacks['title'] = PreambleCmds.title_legacy
        node['classes'] = ['system-message']
        self.visit_admonition(node)
        if self.settings.legacy_class_functions:
            self.out.append('\n\\DUtitle[system-message]{system-message\n')
        else:
            self.out.append('\n\\DUtitle{system-message\n')
        self.append_hypertargets(node)
        try:
            line = ', line~%s' % node['line']
        except KeyError:
            line = ''
        self.out.append('}\n\n{\\color{red}%s/%s} in \\texttt{%s}%s\n' %
                         (node['type'], node['level'],
                          self.encode(node['source']), line))
        if len(node['backrefs']) == 1:
            self.out.append('\n\\hyperlink{%s}{' % node['backrefs'][0])
            self.context.append('}')
        else:
            backrefs = ['\\hyperlink{%s}{%d}' % (href, i+1)
                        for (i, href) in enumerate(node['backrefs'])]
            self.context.append('backrefs: ' + ' '.join(backrefs))

    def depart_system_message(self, node):
        self.out.append(self.context.pop())
        self.depart_admonition(node)

    def visit_table(self, node):
        self.duclass_open(node)
        self.requirements['table'] = PreambleCmds.table
        if self.active_table.is_open():
            self.table_stack.append(self.active_table)
            # nesting longtable does not work (e.g. 2007-04-18)
            # TODO: don't use a longtable or add \noindent before
            #       the next paragraph, when in a "compound paragraph".
            self.active_table = Table(self, 'tabular')
        # A longtable moves before \paragraph and \subparagraph
        # section titles if it immediately follows them:
        if (self.active_table._latex_type == 'longtable' and
            isinstance(node.parent, nodes.section) and
            node.parent.index(node) == 1 and
            self.d_class.section(self.section_level).find('paragraph') != -1):
            self.out.append('\\leavevmode')
        self.active_table.open()
        self.active_table.set_table_style(self.settings.table_style,
                                          node['classes'])
        if 'align' in node:
            self.active_table.set('align', node['align'])
        if self.active_table.borders == 'booktabs':
            self.requirements['booktabs'] = r'\usepackage{booktabs}'
        self.push_output_collector([])

    def depart_table(self, node):
        # wrap content in the right environment:
        content = self.out
        self.pop_output_collector()
        try:
            width = self.to_latex_length(node.attributes['width'])
        except KeyError:
            width = r'\linewidth'
        if isinstance(node.parent, nodes.compound):
            self.out.append('\n')
        self.out.append(self.active_table.get_opening(width))
        self.out += content
        self.out.append(self.active_table.get_closing() + '\n')
        self.active_table.close()
        if len(self.table_stack)>0:
            self.active_table = self.table_stack.pop()
        # Insert hyperlabel after (long)table, as
        # other places (beginning, caption) result in LaTeX errors.
        if node.get('ids'):
            self.out += self.ids_to_labels(node, set_anchor=False) + ['\n']
        self.duclass_close(node)

    def visit_target(self, node):
        # Skip indirect targets:
        if ('refuri' in node       # external hyperlink
            or 'refid' in node     # resolved internal link
            or 'refname' in node): # unresolved internal link
            ## self.out.append('%% %s\n' % node)   # for debugging
            return
        self.out.append('%\n')
        # do we need an anchor (\phantomsection)?
        set_anchor = not isinstance(node.parent, (nodes.caption, nodes.title))
        # TODO: where else can/must we omit the \phantomsection?
        self.out += self.ids_to_labels(node, set_anchor)

    def depart_target(self, node):
        pass

    def visit_tbody(self, node):
        # BUG write preamble if not yet done (colspecs not [])
        # for tables without heads.
        if not self.active_table.get('preamble written'):
            self.visit_thead(node)
            self.depart_thead(None)

    def depart_tbody(self, node):
        pass

    def visit_term(self, node):
        """definition list term"""
        # Commands with optional args inside an optional arg must be put
        # in a group, e.g. ``\item[{\hyperref[label]{text}}]``.
        self.out.append('\\item[{')

    def depart_term(self, node):
        self.out.append('}] ')
        # Do we need a \leavevmode (line break if the field body begins
        # with a list or environment)?
        next_node = node.next_node(descend=False, siblings=True)
        if not isinstance(next_node, nodes.classifier):
            self.out.append(self.term_postfix(next_node))

    def visit_tgroup(self, node):
        pass

    def depart_tgroup(self, node):
        pass

    _thead_depth = 0
    def thead_depth (self):
        return self._thead_depth

    def visit_thead(self, node):
        self._thead_depth += 1
        if 1 == self.thead_depth():
            self.out.append('{%s}\n' % self.active_table.get_colspecs(node))
            self.active_table.set('preamble written', 1)
        self.out.append(self.active_table.get_caption())
        self.out.extend(self.active_table.visit_thead())

    def depart_thead(self, node):
        if node is not None:
            self.out.extend(self.active_table.depart_thead())
            if self.active_table.need_recurse():
                node.walkabout(self)
        self._thead_depth -= 1

    def visit_title(self, node):
        """Append section and other titles."""
        # Document title
        if isinstance(node.parent, nodes.document):
            self.push_output_collector(self.title)
            self.context.append('')
            self.pdfinfo.append('  pdftitle={%s},' %
                                self.encode(node.astext()))
        # Topic titles (topic, admonition, sidebar)
        elif (isinstance(node.parent, nodes.topic) or
              isinstance(node.parent, nodes.admonition) or
              isinstance(node.parent, nodes.sidebar)):
            classes = node.parent['classes'] or [node.parent.tagname]
            if self.settings.legacy_class_functions:
                self.fallbacks['title'] = PreambleCmds.title_legacy
                self.out.append('\n\\DUtitle[%s]{' % ','.join(classes))
            else:
                if not self.fallback_stylesheet:
                    self.fallbacks['title'] = PreambleCmds.title
                self.out.append('\n\\DUtitle{')
            self.context.append('}\n')
        # Table caption
        elif isinstance(node.parent, nodes.table):
            self.push_output_collector(self.active_table.caption)
            self.context.append('')
        # Section title
        else:
            if hasattr(PreambleCmds, 'secnumdepth'):
                self.requirements['secnumdepth'] = PreambleCmds.secnumdepth
            level = self.section_level
            section_name = self.d_class.section(level)
            self.out.append('\n\n')
            if level > len(self.d_class.sections):
                # section level not supported by LaTeX
                if self.settings.legacy_class_functions:
                    self.fallbacks['title'] = PreambleCmds.title_legacy
                    section_name += '[section%s]' % roman.toRoman(level)
                else:
                    if not self.fallback_stylesheet:
                        self.fallbacks['title'] = PreambleCmds.title
                        self.fallbacks['DUclass'] = PreambleCmds.duclass
                    self.out.append('\\begin{DUclass}{section%s}\n'
                                    % roman.toRoman(level))

            # System messages heading in red:
            if ('system-messages' in node.parent['classes']):
                self.requirements['color'] = PreambleCmds.color
                section_title = self.encode(node.astext())
                self.out.append(r'\%s[%s]{\color{red}' % (
                                section_name, section_title))
            else:
                self.out.append(r'\%s{' % section_name)

            # label and ToC entry:
            bookmark = ['']
            # add sections with unsupported level to toc and pdfbookmarks?
            ## if level > len(self.d_class.sections):
            ##     section_title = self.encode(node.astext())
            ##     bookmark.append(r'\addcontentsline{toc}{%s}{%s}' %
            ##               (section_name, section_title))
            bookmark += self.ids_to_labels(node.parent, set_anchor=False)
            self.context.append('%\n  '.join(bookmark) + '%\n}\n')
            if (level > len(self.d_class.sections)
                and not self.settings.legacy_class_functions):
                self.context[-1] += '\\end{DUclass}\n'
            # MAYBE postfix paragraph and subparagraph with \leavemode to
            # ensure floats stay in the section and text starts on a new line.

    def depart_title(self, node):
        self.out.append(self.context.pop())
        if isinstance(node.parent, (nodes.table, nodes.document)):
            self.pop_output_collector()

    def minitoc(self, node, title, depth):
        """Generate a local table of contents with LaTeX package minitoc"""
        section_name = self.d_class.section(self.section_level)
        # name-prefix for current section level
        minitoc_names = {'part': 'part', 'chapter': 'mini'}
        if 'chapter' not in self.d_class.sections:
            minitoc_names['section'] = 'sect'
        try:
            minitoc_name = minitoc_names[section_name]
        except KeyError: # minitoc only supports part- and toplevel
            self.warn('Skipping local ToC at %s level.\n' % section_name +
                      '  Feature not supported with option "use-latex-toc"',
                      base_node=node)
            return
        # Requirements/Setup
        self.requirements['minitoc'] = PreambleCmds.minitoc
        self.requirements['minitoc-'+minitoc_name] = (r'\do%stoc' %
                                                      minitoc_name)
        # depth: (Docutils defaults to unlimited depth)
        maxdepth = len(self.d_class.sections)
        self.requirements['minitoc-%s-depth' % minitoc_name] = (
            r'\mtcsetdepth{%stoc}{%d}' % (minitoc_name, maxdepth))
        # Process 'depth' argument (!Docutils stores a relative depth while
        # minitoc  expects an absolute depth!):
        offset = {'sect': 1, 'mini': 0, 'part': 0}
        if 'chapter' in self.d_class.sections:
            offset['part'] = -1
        if depth:
            self.out.append('\\setcounter{%stocdepth}{%d}' %
                             (minitoc_name, depth + offset[minitoc_name]))
        # title:
        self.out.append('\\mtcsettitle{%stoc}{%s}\n' % (minitoc_name, title))
        # the toc-generating command:
        self.out.append('\\%stoc\n' % minitoc_name)

    def visit_topic(self, node):
        # Topic nodes can be generic topic, abstract, dedication, or ToC.
        # table of contents:
        if 'contents' in node['classes']:
            self.out.append('\n')
            self.out += self.ids_to_labels(node)
            # add contents to PDF bookmarks sidebar
            if (isinstance(node.next_node(), nodes.title)
                and self.settings.documentclass != 'memoir'):
                self.out.append('\n\\pdfbookmark[%d]{%s}{%s}' %
                                (self.section_level+1,
                                 node.next_node().astext(),
                                 node.get('ids', ['contents'])[0]
                                ))
            if self.use_latex_toc:
                title = ''
                if isinstance(node.next_node(), nodes.title):
                    title = self.encode(node.pop(0).astext())
                depth = node.get('depth', 0)
                if 'local' in node['classes']:
                    self.minitoc(node, title, depth)
                    return
                if depth:
                    self.out.append('\\setcounter{tocdepth}{%d}\n' % depth)
                if title != 'Contents':
                    self.out.append('\n\\renewcommand{\\contentsname}{%s}' %
                                    title)
                self.out.append('\n\\tableofcontents\n')
                self.has_latex_toc = True
                # ignore rest of node content
                raise nodes.SkipNode
            else: # Docutils generated contents list
                # set flag for visit_bullet_list() and visit_title()
                self.is_toc_list = True
        elif ('abstract' in node['classes'] and
              self.settings.use_latex_abstract):
            self.push_output_collector(self.abstract)
            self.out.append('\\begin{abstract}')
            if isinstance(node.next_node(), nodes.title):
                node.pop(0) # LaTeX provides its own title
        else:
            # special topics:
            if 'abstract' in node['classes']:
                if not self.fallback_stylesheet:
                    self.fallbacks['abstract'] = PreambleCmds.abstract
                if self.settings.legacy_class_functions:
                    self.fallbacks['abstract'] = PreambleCmds.abstract_legacy
                self.push_output_collector(self.abstract)
            elif 'dedication' in node['classes']:
                if not self.fallback_stylesheet:
                    self.fallbacks['dedication'] = PreambleCmds.dedication
                self.push_output_collector(self.dedication)
            else:
                node['classes'].insert(0, 'topic')
            self.visit_block_quote(node)

    def depart_topic(self, node):
        self.is_toc_list = False
        if ('abstract' in node['classes']
          and self.settings.use_latex_abstract):
            self.out.append('\\end{abstract}\n')
        elif not 'contents' in node['classes']:
            self.depart_block_quote(node)
        if ('abstract' in node['classes'] or
            'dedication' in node['classes']):
            self.pop_output_collector()

    def visit_transition(self, node):
        if not self.fallback_stylesheet:
            self.fallbacks['transition'] = PreambleCmds.transition
        self.out.append('\n%' + '_' * 75 + '\n')
        self.out.append('\\DUtransition\n')

    def depart_transition(self, node):
        pass

    def visit_version(self, node):
        self.visit_docinfo_item(node, 'version')

    def depart_version(self, node):
        self.depart_docinfo_item(node)

    def unimplemented_visit(self, node):
        raise NotImplementedError('visiting unimplemented node type: %s' %
                                  node.__class__.__name__)

#    def unknown_visit(self, node):
#    def default_visit(self, node):

# vim: set ts=4 et ai :