File: __init__.py

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

"""
Open Document Format (ODF) Writer.

"""

VERSION = '1.0a'

__docformat__ = 'reStructuredText'


import sys
import os
import os.path
import tempfile
import zipfile
from xml.dom import minidom
import time
import re
import StringIO
import copy
import urllib2
import docutils
from docutils import frontend, nodes, utils, writers, languages
from docutils.readers import standalone
from docutils.transforms import references


WhichElementTree = ''
try:
    # 1. Try to use lxml.
    #from lxml import etree
    #WhichElementTree = 'lxml'
    raise ImportError('Ignoring lxml')
except ImportError, e:
    try:
        # 2. Try to use ElementTree from the Python standard library.
        from xml.etree import ElementTree as etree
        WhichElementTree = 'elementtree'
    except ImportError, e:
        try:
            # 3. Try to use a version of ElementTree installed as a separate
            #    product.
            from elementtree import ElementTree as etree
            WhichElementTree = 'elementtree'
        except ImportError, e:
            s1 = 'Must install either a version of Python containing ' \
                 'ElementTree (Python version >=2.5) or install ElementTree.'
            raise ImportError(s1)

#
# Import pygments and odtwriter pygments formatters if possible.
try:
    import pygments
    import pygments.lexers
    from pygmentsformatter import OdtPygmentsProgFormatter, \
        OdtPygmentsLaTeXFormatter
except ImportError, exp:
    pygments = None

# check for the Python Imaging Library
try:
    import PIL.Image
except ImportError:
    try:  # sometimes PIL modules are put in PYTHONPATH's root
        import Image
        class PIL(object): pass  # dummy wrapper
        PIL.Image = Image
    except ImportError:
        PIL = None

## import warnings
## warnings.warn('importing IPShellEmbed', UserWarning)
## from IPython.Shell import IPShellEmbed
## args = ['-pdb', '-pi1', 'In <\\#>: ', '-pi2', '   .\\D.: ',
##         '-po', 'Out<\\#>: ', '-nosep']
## ipshell = IPShellEmbed(args,
##                        banner = 'Entering IPython.  Press Ctrl-D to exit.',
##                        exit_msg = 'Leaving Interpreter, back to program.')


#
# ElementTree does not support getparent method (lxml does).
# This wrapper class and the following support functions provide
#   that support for the ability to get the parent of an element.
#
if WhichElementTree == 'elementtree':
    import weakref
    _parents = weakref.WeakKeyDictionary()
    if isinstance(etree.Element, type):
        _ElementInterface = etree.Element
    else:
        _ElementInterface = etree._ElementInterface
    class _ElementInterfaceWrapper(_ElementInterface):
        def __init__(self, tag, attrib=None):
            _ElementInterface.__init__(self, tag, attrib)
            _parents[self] = None
        def setparent(self, parent):
            _parents[self] = parent
        def getparent(self):
            return _parents[self]


#
# Constants and globals

SPACES_PATTERN = re.compile(r'( +)')
TABS_PATTERN = re.compile(r'(\t+)')
FILL_PAT1 = re.compile(r'^ +')
FILL_PAT2 = re.compile(r' {2,}')

TABLESTYLEPREFIX = 'rststyle-table-'
TABLENAMEDEFAULT = '%s0' % TABLESTYLEPREFIX
TABLEPROPERTYNAMES = ('border', 'border-top', 'border-left',
    'border-right', 'border-bottom', )

GENERATOR_DESC = 'Docutils.org/odf_odt'

NAME_SPACE_1 = 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'

CONTENT_NAMESPACE_DICT = CNSD = {
#    'office:version': '1.0',
    'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
    'dc': 'http://purl.org/dc/elements/1.1/',
    'dom': 'http://www.w3.org/2001/xml-events',
    'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
    'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
    'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
    'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
    'math': 'http://www.w3.org/1998/Math/MathML',
    'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
    'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
    'office': NAME_SPACE_1,
    'ooo': 'http://openoffice.org/2004/office',
    'oooc': 'http://openoffice.org/2004/calc',
    'ooow': 'http://openoffice.org/2004/writer',
    'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',

    'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
    'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
    'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
    'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
    'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
    'xforms': 'http://www.w3.org/2002/xforms',
    'xlink': 'http://www.w3.org/1999/xlink',
    'xsd': 'http://www.w3.org/2001/XMLSchema',
    'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
    }

STYLES_NAMESPACE_DICT = SNSD = {
#    'office:version': '1.0',
    'chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
    'dc': 'http://purl.org/dc/elements/1.1/',
    'dom': 'http://www.w3.org/2001/xml-events',
    'dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
    'draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
    'fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
    'form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
    'math': 'http://www.w3.org/1998/Math/MathML',
    'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
    'number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
    'office': NAME_SPACE_1,
    'presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
    'ooo': 'http://openoffice.org/2004/office',
    'oooc': 'http://openoffice.org/2004/calc',
    'ooow': 'http://openoffice.org/2004/writer',
    'script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
    'style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
    'svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
    'table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
    'text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
    'xlink': 'http://www.w3.org/1999/xlink',
    }

MANIFEST_NAMESPACE_DICT = MANNSD = {
    'manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}

META_NAMESPACE_DICT = METNSD = {
#    'office:version': '1.0',
    'dc': 'http://purl.org/dc/elements/1.1/',
    'meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
    'office': NAME_SPACE_1,
    'ooo': 'http://openoffice.org/2004/office',
    'xlink': 'http://www.w3.org/1999/xlink',
}

#
# Attribute dictionaries for use with ElementTree (not lxml), which
#   does not support use of nsmap parameter on Element() and SubElement().

CONTENT_NAMESPACE_ATTRIB = {
    #'office:version': '1.0',
    'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
    'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
    'xmlns:dom': 'http://www.w3.org/2001/xml-events',
    'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
    'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
    'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
    'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
    'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
    'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
    'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
    'xmlns:office': NAME_SPACE_1,
    'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
    'xmlns:ooo': 'http://openoffice.org/2004/office',
    'xmlns:oooc': 'http://openoffice.org/2004/calc',
    'xmlns:ooow': 'http://openoffice.org/2004/writer',
    'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
    'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
    'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
    'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
    'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
    'xmlns:xforms': 'http://www.w3.org/2002/xforms',
    'xmlns:xlink': 'http://www.w3.org/1999/xlink',
    'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
    'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
    }

STYLES_NAMESPACE_ATTRIB = {
    #'office:version': '1.0',
    'xmlns:chart': 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0',
    'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
    'xmlns:dom': 'http://www.w3.org/2001/xml-events',
    'xmlns:dr3d': 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0',
    'xmlns:draw': 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0',
    'xmlns:fo': 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0',
    'xmlns:form': 'urn:oasis:names:tc:opendocument:xmlns:form:1.0',
    'xmlns:math': 'http://www.w3.org/1998/Math/MathML',
    'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
    'xmlns:number': 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0',
    'xmlns:office': NAME_SPACE_1,
    'xmlns:presentation': 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0',
    'xmlns:ooo': 'http://openoffice.org/2004/office',
    'xmlns:oooc': 'http://openoffice.org/2004/calc',
    'xmlns:ooow': 'http://openoffice.org/2004/writer',
    'xmlns:script': 'urn:oasis:names:tc:opendocument:xmlns:script:1.0',
    'xmlns:style': 'urn:oasis:names:tc:opendocument:xmlns:style:1.0',
    'xmlns:svg': 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0',
    'xmlns:table': 'urn:oasis:names:tc:opendocument:xmlns:table:1.0',
    'xmlns:text': 'urn:oasis:names:tc:opendocument:xmlns:text:1.0',
    'xmlns:xlink': 'http://www.w3.org/1999/xlink',
    }

MANIFEST_NAMESPACE_ATTRIB = {
    'xmlns:manifest': 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0',
}

META_NAMESPACE_ATTRIB = {
    #'office:version': '1.0',
    'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
    'xmlns:meta': 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0',
    'xmlns:office': NAME_SPACE_1,
    'xmlns:ooo': 'http://openoffice.org/2004/office',
    'xmlns:xlink': 'http://www.w3.org/1999/xlink',
}


#
# Functions
#

#
# ElementTree support functions.
# In order to be able to get the parent of elements, must use these
#   instead of the functions with same name provided by ElementTree.
#
def Element(tag, attrib=None, nsmap=None, nsdict=CNSD):
    if attrib is None:
        attrib = {}
    tag, attrib = fix_ns(tag, attrib, nsdict)
    if WhichElementTree == 'lxml':
        el = etree.Element(tag, attrib, nsmap=nsmap)
    else:
        el = _ElementInterfaceWrapper(tag, attrib)
    return el

def SubElement(parent, tag, attrib=None, nsmap=None, nsdict=CNSD):
    if attrib is None:
        attrib = {}
    tag, attrib = fix_ns(tag, attrib, nsdict)
    if WhichElementTree == 'lxml':
        el = etree.SubElement(parent, tag, attrib, nsmap=nsmap)
    else:
        el = _ElementInterfaceWrapper(tag, attrib)
        parent.append(el)
        el.setparent(parent)
    return el

def fix_ns(tag, attrib, nsdict):
    nstag = add_ns(tag, nsdict)
    nsattrib = {}
    for key, val in attrib.iteritems():
        nskey = add_ns(key, nsdict)
        nsattrib[nskey] = val
    return nstag, nsattrib

def add_ns(tag, nsdict=CNSD):
    if WhichElementTree == 'lxml':
        nstag, name = tag.split(':')
        ns = nsdict.get(nstag)
        if ns is None:
            raise RuntimeError, 'Invalid namespace prefix: %s' % nstag
        tag = '{%s}%s' % (ns, name,)
    return tag

def ToString(et):
    outstream = StringIO.StringIO()
    if sys.version_info >= (3, 2):
        et.write(outstream, encoding="unicode")
    else:
        et.write(outstream)
    s1 = outstream.getvalue()
    outstream.close()
    return s1


def escape_cdata(text):
    text = text.replace("&", "&amp;")
    text = text.replace("<", "&lt;")
    text = text.replace(">", "&gt;")
    ascii = ''
    for char in text:
      if ord(char) >= ord("\x7f"):
          ascii += "&#x%X;" % ( ord(char), )
      else:
          ascii += char
    return ascii



WORD_SPLIT_PAT1 = re.compile(r'\b(\w*)\b\W*')

def split_words(line):
    # We need whitespace at the end of the string for our regexpr.
    line += ' '
    words = []
    pos1 = 0
    mo = WORD_SPLIT_PAT1.search(line, pos1)
    while mo is not None:
        word = mo.groups()[0]
        words.append(word)
        pos1 = mo.end()
        mo = WORD_SPLIT_PAT1.search(line, pos1)
    return words


#
# Classes
#


class TableStyle(object):
    def __init__(self, border=None, backgroundcolor=None):
        self.border = border
        self.backgroundcolor = backgroundcolor
    def get_border_(self):
        return self.border_
    def set_border_(self, border):
        self.border_ = border
    border = property(get_border_, set_border_)
    def get_backgroundcolor_(self):
        return self.backgroundcolor_
    def set_backgroundcolor_(self, backgroundcolor):
        self.backgroundcolor_ = backgroundcolor
    backgroundcolor = property(get_backgroundcolor_, set_backgroundcolor_)

BUILTIN_DEFAULT_TABLE_STYLE = TableStyle(
    border = '0.0007in solid #000000')

#
# Information about the indentation level for lists nested inside
#   other contexts, e.g. dictionary lists.
class ListLevel(object):
    def __init__(self, level, sibling_level=True, nested_level=True):
        self.level = level
        self.sibling_level = sibling_level
        self.nested_level = nested_level
    def set_sibling(self, sibling_level): self.sibling_level = sibling_level
    def get_sibling(self): return self.sibling_level
    def set_nested(self, nested_level): self.nested_level = nested_level
    def get_nested(self): return self.nested_level
    def set_level(self, level): self.level = level
    def get_level(self): return self.level


class Writer(writers.Writer):

    MIME_TYPE = 'application/vnd.oasis.opendocument.text'
    EXTENSION = '.odt'

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

    default_stylesheet = 'styles' + EXTENSION

    default_stylesheet_path = utils.relative_path(
        os.path.join(os.getcwd(), 'dummy'),
        os.path.join(docutils._datadir(__file__), default_stylesheet))

    default_template = 'template.txt'

    default_template_path = utils.relative_path(
        os.path.join(os.getcwd(), 'dummy'),
        os.path.join(docutils._datadir(__file__), default_template))

    settings_spec = (
        'ODF-Specific Options',
        None,
        (
        ('Specify a stylesheet.  '
            'Default: "%s"' % default_stylesheet_path,
            ['--stylesheet'],
            {
                'default': default_stylesheet_path,
                'dest': 'stylesheet'
                }),
        ('Specify a configuration/mapping file relative to the '
            'current working '
            'directory for additional ODF options.  '
            'In particular, this file may contain a section named '
            '"Formats" that maps default style names to '
            'names to be used in the resulting output file allowing for '
            'adhering to external standards. '
            'For more info and the format of the configuration/mapping file, '
            'see the odtwriter doc.',
            ['--odf-config-file'],
            {'metavar': '<file>'}),
        ('Obfuscate email addresses to confuse harvesters while still '
            'keeping email links usable with standards-compliant browsers.',
            ['--cloak-email-addresses'],
            {'default': False,
                'action': 'store_true',
                'dest': 'cloak_email_addresses',
                'validator': frontend.validate_boolean}),
        ('Do not obfuscate email addresses.',
            ['--no-cloak-email-addresses'],
            {'default': False,
                'action': 'store_false',
                'dest': 'cloak_email_addresses',
                'validator': frontend.validate_boolean}),
        ('Specify the thickness of table borders in thousands of a cm.  '
            'Default is 35.',
            ['--table-border-thickness'],
            {'default': None,
                'validator': frontend.validate_nonnegative_int}),
        ('Add syntax highlighting in literal code blocks.',
            ['--add-syntax-highlighting'],
            {'default': False,
                'action': 'store_true',
                'dest': 'add_syntax_highlighting',
                'validator': frontend.validate_boolean}),
        ('Do not add syntax highlighting in literal code blocks. (default)',
            ['--no-syntax-highlighting'],
            {'default': False,
                'action': 'store_false',
                'dest': 'add_syntax_highlighting',
                'validator': frontend.validate_boolean}),
        ('Create sections for headers.  (default)',
            ['--create-sections'],
            {'default': True, 
                'action': 'store_true',
                'dest': 'create_sections',
                'validator': frontend.validate_boolean}),
        ('Do not create sections for headers.',
            ['--no-sections'],
            {'default': True, 
                'action': 'store_false',
                'dest': 'create_sections',
                'validator': frontend.validate_boolean}),
        ('Create links.',
            ['--create-links'],
            {'default': False,
                'action': 'store_true',
                'dest': 'create_links',
                'validator': frontend.validate_boolean}),
        ('Do not create links.  (default)',
            ['--no-links'],
            {'default': False,
                'action': 'store_false',
                'dest': 'create_links',
                'validator': frontend.validate_boolean}),
        ('Generate endnotes at end of document, not footnotes '
            'at bottom of page.',
            ['--endnotes-end-doc'],
            {'default': False,
                'action': 'store_true',
                'dest': 'endnotes_end_doc',
                'validator': frontend.validate_boolean}),
        ('Generate footnotes at bottom of page, not endnotes '
            'at end of document. (default)',
            ['--no-endnotes-end-doc'],
            {'default': False,
                'action': 'store_false',
                'dest': 'endnotes_end_doc',
                'validator': frontend.validate_boolean}),
        ('Generate a bullet list table of contents, not '
            'an ODF/oowriter table of contents.',
            ['--generate-list-toc'],
            {'default': True,
                'action': 'store_false',
                'dest': 'generate_oowriter_toc',
                'validator': frontend.validate_boolean}),
        ('Generate an ODF/oowriter table of contents, not '
            'a bullet list. (default)',
            ['--generate-oowriter-toc'],
            {'default': True,
                'action': 'store_true',
                'dest': 'generate_oowriter_toc',
                'validator': frontend.validate_boolean}),
        ('Specify the contents of an custom header line.  '
            'See odf_odt writer documentation for details '
            'about special field character sequences.',
            ['--custom-odt-header'],
            {   'default': '',
                'dest': 'custom_header',
                }),
        ('Specify the contents of an custom footer line.  '
            'See odf_odt writer documentation for details '
            'about special field character sequences.',
            ['--custom-odt-footer'],
            {   'default': '',
                'dest': 'custom_footer',
                }),
        )
        )

    settings_defaults = {
        'output_encoding_error_handler': 'xmlcharrefreplace',
        }

    relative_path_settings = (
        'stylesheet_path',
        )

    config_section = 'odf_odt writer'
    config_section_dependencies = (
        'writers',
        )

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

    def translate(self):
        self.settings = self.document.settings
        self.visitor = self.translator_class(self.document)
        self.visitor.retrieve_styles(self.EXTENSION)
        self.document.walkabout(self.visitor)
        self.visitor.add_doc_title()
        self.assemble_my_parts()
        self.output = self.parts['whole']

    def assemble_my_parts(self):
        """Assemble the `self.parts` dictionary.  Extend in subclasses.
        """
        writers.Writer.assemble_parts(self)
        f = tempfile.NamedTemporaryFile()
        zfile = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
        self.write_zip_str(zfile, 'mimetype', self.MIME_TYPE,
            compress_type=zipfile.ZIP_STORED)
        content = self.visitor.content_astext()
        self.write_zip_str(zfile, 'content.xml', content)
        s1 = self.create_manifest()
        self.write_zip_str(zfile, 'META-INF/manifest.xml', s1)
        s1 = self.create_meta()
        self.write_zip_str(zfile, 'meta.xml', s1)
        s1 = self.get_stylesheet()
        self.write_zip_str(zfile, 'styles.xml', s1)
        self.store_embedded_files(zfile)
        self.copy_from_stylesheet(zfile)
        zfile.close()
        f.seek(0)
        whole = f.read()
        f.close()
        self.parts['whole'] = whole
        self.parts['encoding'] = self.document.settings.output_encoding
        self.parts['version'] = docutils.__version__

    def write_zip_str(self, zfile, name, bytes, compress_type=zipfile.ZIP_DEFLATED):
        localtime = time.localtime(time.time())
        zinfo = zipfile.ZipInfo(name, localtime)
        # Add some standard UNIX file access permissions (-rw-r--r--).
        zinfo.external_attr = (0x81a4 & 0xFFFF) << 16L
        zinfo.compress_type = compress_type
        zfile.writestr(zinfo, bytes)

    def store_embedded_files(self, zfile):
        embedded_files = self.visitor.get_embedded_file_list()
        for source, destination in embedded_files:
            if source is None:
                continue
            try:
                # encode/decode
                zfile.write(source, destination)
            except OSError, e:
                self.document.reporter.warning(
                    "Can't open file %s." % (source, ))

    def get_settings(self):
        """
        modeled after get_stylesheet
        """
        stylespath = self.settings.stylesheet
        zfile = zipfile.ZipFile(stylespath, 'r')
        s1 = zfile.read('settings.xml')
        zfile.close()
        return s1

    def get_stylesheet(self):
        """Get the stylesheet from the visitor.
        Ask the visitor to setup the page.
        """
        s1 = self.visitor.setup_page()
        return s1

    def copy_from_stylesheet(self, outzipfile):
        """Copy images, settings, etc from the stylesheet doc into target doc.
        """
        stylespath = self.settings.stylesheet
        inzipfile = zipfile.ZipFile(stylespath, 'r')
        # Copy the styles.
        s1 = inzipfile.read('settings.xml')
        self.write_zip_str(outzipfile, 'settings.xml', s1)
        # Copy the images.
        namelist = inzipfile.namelist()
        for name in namelist:
            if name.startswith('Pictures/'):
                imageobj = inzipfile.read(name)
                outzipfile.writestr(name, imageobj)
        inzipfile.close()

    def assemble_parts(self):
        pass

    def create_manifest(self):
        if WhichElementTree == 'lxml':
            root = Element('manifest:manifest',
                nsmap=MANIFEST_NAMESPACE_DICT,
                nsdict=MANIFEST_NAMESPACE_DICT,
                )
        else:
            root = Element('manifest:manifest',
                attrib=MANIFEST_NAMESPACE_ATTRIB,
                nsdict=MANIFEST_NAMESPACE_DICT,
                )
        doc = etree.ElementTree(root)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': self.MIME_TYPE,
            'manifest:full-path': '/',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'content.xml',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'styles.xml',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'settings.xml',
            }, nsdict=MANNSD)
        SubElement(root, 'manifest:file-entry', attrib={
            'manifest:media-type': 'text/xml',
            'manifest:full-path': 'meta.xml',
            }, nsdict=MANNSD)
        s1 = ToString(doc)
        doc = minidom.parseString(s1)
        s1 = doc.toprettyxml('  ')
        return s1

    def create_meta(self):
        if WhichElementTree == 'lxml':
            root = Element('office:document-meta',
                nsmap=META_NAMESPACE_DICT,
                nsdict=META_NAMESPACE_DICT,
                )
        else:
            root = Element('office:document-meta',
                attrib=META_NAMESPACE_ATTRIB,
                nsdict=META_NAMESPACE_DICT,
                )
        doc = etree.ElementTree(root)
        root = SubElement(root, 'office:meta', nsdict=METNSD)
        el1 = SubElement(root, 'meta:generator', nsdict=METNSD)
        el1.text = 'Docutils/rst2odf.py/%s' % (VERSION, )
        s1 = os.environ.get('USER', '')
        el1 = SubElement(root, 'meta:initial-creator', nsdict=METNSD)
        el1.text = s1
        s2 = time.strftime('%Y-%m-%dT%H:%M:%S', time.localtime())
        el1 = SubElement(root, 'meta:creation-date', nsdict=METNSD)
        el1.text = s2
        el1 = SubElement(root, 'dc:creator', nsdict=METNSD)
        el1.text = s1
        el1 = SubElement(root, 'dc:date', nsdict=METNSD)
        el1.text = s2
        el1 = SubElement(root, 'dc:language', nsdict=METNSD)
        el1.text = 'en-US'
        el1 = SubElement(root, 'meta:editing-cycles', nsdict=METNSD)
        el1.text = '1'
        el1 = SubElement(root, 'meta:editing-duration', nsdict=METNSD)
        el1.text = 'PT00M01S'
        title = self.visitor.get_title()
        el1 = SubElement(root, 'dc:title', nsdict=METNSD)
        if title:
            el1.text = title
        else:
            el1.text = '[no title]'
        meta_dict = self.visitor.get_meta_dict()
        keywordstr = meta_dict.get('keywords')
        if keywordstr is not None:
            keywords = split_words(keywordstr)
            for keyword in keywords:
                el1 = SubElement(root, 'meta:keyword', nsdict=METNSD)
                el1.text = keyword
        description = meta_dict.get('description')
        if description is not None:
            el1 = SubElement(root, 'dc:description', nsdict=METNSD)
            el1.text = description
        s1 = ToString(doc)
        #doc = minidom.parseString(s1)
        #s1 = doc.toprettyxml('  ')
        return s1

# class ODFTranslator(nodes.SparseNodeVisitor):

class ODFTranslator(nodes.GenericNodeVisitor):

    used_styles = (
        'attribution', 'blockindent', 'blockquote', 'blockquote-bulletitem',
        'blockquote-bulletlist', 'blockquote-enumitem', 'blockquote-enumlist',
        'bulletitem', 'bulletlist',
        'caption', 'legend',
        'centeredtextbody', 'codeblock', 'codeblock-indented',
        'codeblock-classname', 'codeblock-comment', 'codeblock-functionname',
        'codeblock-keyword', 'codeblock-name', 'codeblock-number',
        'codeblock-operator', 'codeblock-string', 'emphasis', 'enumitem',
        'enumlist', 'epigraph', 'epigraph-bulletitem', 'epigraph-bulletlist',
        'epigraph-enumitem', 'epigraph-enumlist', 'footer',
        'footnote', 'citation',
        'header', 'highlights', 'highlights-bulletitem',
        'highlights-bulletlist', 'highlights-enumitem', 'highlights-enumlist',
        'horizontalline', 'inlineliteral', 'quotation', 'rubric',
        'strong', 'table-title', 'textbody', 'tocbulletlist', 'tocenumlist',
        'title',
        'subtitle',
        'heading1',
        'heading2',
        'heading3',
        'heading4',
        'heading5',
        'heading6',
        'heading7',
        'admon-attention-hdr',
        'admon-attention-body',
        'admon-caution-hdr',
        'admon-caution-body',
        'admon-danger-hdr',
        'admon-danger-body',
        'admon-error-hdr',
        'admon-error-body',
        'admon-generic-hdr',
        'admon-generic-body',
        'admon-hint-hdr',
        'admon-hint-body',
        'admon-important-hdr',
        'admon-important-body',
        'admon-note-hdr',
        'admon-note-body',
        'admon-tip-hdr',
        'admon-tip-body',
        'admon-warning-hdr',
        'admon-warning-body',
        'tableoption',
        'tableoption.%c', 'tableoption.%c%d', 'Table%d', 'Table%d.%c',
        'Table%d.%c%d',
        'lineblock1',
        'lineblock2',
        'lineblock3',
        'lineblock4',
        'lineblock5',
        'lineblock6',
        'image', 'figureframe',
        )

    def __init__(self, document):
        #nodes.SparseNodeVisitor.__init__(self, document)
        nodes.GenericNodeVisitor.__init__(self, document)
        self.settings = document.settings
        lcode = self.settings.language_code
        self.language = languages.get_language(lcode, document.reporter)
        self.format_map = { }
        if self.settings.odf_config_file:
            from ConfigParser import ConfigParser

            parser = ConfigParser()
            parser.read(self.settings.odf_config_file)
            for rststyle, format in parser.items("Formats"):
                if rststyle not in self.used_styles:
                    self.document.reporter.warning(
                        'Style "%s" is not a style used by odtwriter.' % (
                        rststyle, ))
                self.format_map[rststyle] = format.decode('utf-8')
        self.section_level = 0
        self.section_count = 0
        # Create ElementTree content and styles documents.
        if WhichElementTree == 'lxml':
            root = Element(
                'office:document-content',
                nsmap=CONTENT_NAMESPACE_DICT,
                )
        else:
            root = Element(
                'office:document-content',
                attrib=CONTENT_NAMESPACE_ATTRIB,
                )
        self.content_tree = etree.ElementTree(element=root)
        self.current_element = root
        SubElement(root, 'office:scripts')
        SubElement(root, 'office:font-face-decls')
        el = SubElement(root, 'office:automatic-styles')
        self.automatic_styles = el
        el = SubElement(root, 'office:body')
        el = self.generate_content_element(el)
        self.current_element = el
        self.body_text_element = el
        self.paragraph_style_stack = [self.rststyle('textbody'), ]
        self.list_style_stack = []
        self.table_count = 0
        self.column_count = ord('A') - 1
        self.trace_level = -1
        self.optiontablestyles_generated = False
        self.field_name = None
        self.field_element = None
        self.title = None
        self.image_count = 0
        self.image_style_count = 0
        self.image_dict = {}
        self.embedded_file_list = []
        self.syntaxhighlighting = 1
        self.syntaxhighlight_lexer = 'python'
        self.header_content = []
        self.footer_content = []
        self.in_header = False
        self.in_footer = False
        self.blockstyle = ''
        self.in_table_of_contents = False
        self.table_of_content_index_body = None
        self.list_level = 0
        self.def_list_level = 0
        self.footnote_ref_dict = {}
        self.footnote_list = []
        self.footnote_chars_idx = 0
        self.footnote_level = 0
        self.pending_ids = [ ]
        self.in_paragraph = False
        self.found_doc_title = False
        self.bumped_list_level_stack = []
        self.meta_dict = {}
        self.line_block_level = 0
        self.line_indent_level = 0
        self.citation_id = None
        self.style_index = 0        # use to form unique style names
        self.str_stylesheet = ''
        self.str_stylesheetcontent = ''
        self.dom_stylesheet = None
        self.table_styles = None
        self.in_citation = False


    def get_str_stylesheet(self):
        return self.str_stylesheet

    def retrieve_styles(self, extension):
        """Retrieve the stylesheet from either a .xml file or from
        a .odt (zip) file.  Return the content as a string.
        """
        s2 = None
        stylespath = self.settings.stylesheet
        ext = os.path.splitext(stylespath)[1]
        if ext == '.xml':
            stylesfile = open(stylespath, 'r')
            s1 = stylesfile.read()
            stylesfile.close()
        elif ext == extension:
            zfile = zipfile.ZipFile(stylespath, 'r')
            s1 = zfile.read('styles.xml')
            s2 = zfile.read('content.xml')
            zfile.close()
        else:
            raise RuntimeError, 'stylesheet path (%s) must be %s or .xml file' %(stylespath, extension)
        self.str_stylesheet = s1
        self.str_stylesheetcontent = s2
        self.dom_stylesheet = etree.fromstring(self.str_stylesheet)
        self.dom_stylesheetcontent = etree.fromstring(self.str_stylesheetcontent)
        self.table_styles = self.extract_table_styles(s2)

    def extract_table_styles(self, styles_str):
        root = etree.fromstring(styles_str)
        table_styles = {}
        auto_styles = root.find(
            '{%s}automatic-styles' % (CNSD['office'], ))
        for stylenode in auto_styles:
            name = stylenode.get('{%s}name' % (CNSD['style'], ))
            tablename = name.split('.')[0]
            family = stylenode.get('{%s}family' % (CNSD['style'], ))
            if name.startswith(TABLESTYLEPREFIX):
                tablestyle = table_styles.get(tablename)
                if tablestyle is None:
                    tablestyle = TableStyle()
                    table_styles[tablename] = tablestyle
                if family == 'table':
                    properties = stylenode.find(
                        '{%s}table-properties' % (CNSD['style'], ))
                    property = properties.get('{%s}%s' % (CNSD['fo'],
                        'background-color', ))
                    if property is not None and property != 'none':
                        tablestyle.backgroundcolor = property
                elif family == 'table-cell':
                    properties = stylenode.find(
                        '{%s}table-cell-properties' % (CNSD['style'], ))
                    if properties is not None:
                        border = self.get_property(properties)
                        if border is not None:
                            tablestyle.border = border
        return table_styles

    def get_property(self, stylenode):
        border = None
        for propertyname in TABLEPROPERTYNAMES:
            border = stylenode.get('{%s}%s' % (CNSD['fo'], propertyname, ))
            if border is not None and border != 'none':
                return border
        return border

    def add_doc_title(self):
        text = self.settings.title
        if text:
            self.title = text
            if not self.found_doc_title:
                el = Element('text:p', attrib = {
                    'text:style-name': self.rststyle('title'),
                    })
                el.text = text
                self.body_text_element.insert(0, el)
        el = self.find_first_text_p(self.body_text_element)
        if el is not None:
            self.attach_page_style(el)

    def find_first_text_p(self, el):
        """Search the generated doc and return the first <text:p> element.
        """
        if (
                el.tag == 'text:p' or
                el.tag == 'text:h'
                ):
            return el
        elif el.getchildren():
            for child in el.getchildren():
                el1 = self.find_first_text_p(child)
                if el1 is not None:
                    return el1
            return None
        else:
            return None

    def attach_page_style(self, el):
        """Attach the default page style.

        Create an automatic-style that refers to the current style
        of this element and that refers to the default page style.
        """
        current_style = el.get('text:style-name')
        style_name = 'P1003'
        el1 = SubElement(
            self.automatic_styles, 'style:style', attrib={
                'style:name': style_name,
                'style:master-page-name': "rststyle-pagedefault",
                'style:family': "paragraph",
                }, nsdict=SNSD)
        if current_style:
            el1.set('style:parent-style-name', current_style)
        el.set('text:style-name', style_name)


    def rststyle(self, name, parameters=( )):
        """
        Returns the style name to use for the given style.

        If `parameters` is given `name` must contain a matching number of ``%`` and
        is used as a format expression with `parameters` as the value.
        """
        name1 = name % parameters
        stylename = self.format_map.get(name1, 'rststyle-%s' % name1)
        return stylename

    def generate_content_element(self, root):
        return SubElement(root, 'office:text')

    def setup_page(self):
        self.setup_paper(self.dom_stylesheet)
        if (len(self.header_content) > 0 or len(self.footer_content) > 0 or
            self.settings.custom_header or self.settings.custom_footer):
            self.add_header_footer(self.dom_stylesheet)
        new_content = etree.tostring(self.dom_stylesheet)
        return new_content

    def setup_paper(self, root_el):
        try:
            fin = os.popen("paperconf -s 2> /dev/null")
            w, h = map(float, fin.read().split())
            fin.close()
        except:
            w, h = 612, 792     # default to Letter
        def walk(el):
            if el.tag == "{%s}page-layout-properties" % SNSD["style"] and \
                    not el.attrib.has_key("{%s}page-width" % SNSD["fo"]):
                el.attrib["{%s}page-width" % SNSD["fo"]] = "%.3fpt" % w
                el.attrib["{%s}page-height" % SNSD["fo"]] = "%.3fpt" % h
                el.attrib["{%s}margin-left" % SNSD["fo"]] = \
                        el.attrib["{%s}margin-right" % SNSD["fo"]] = \
                        "%.3fpt" % (.1 * w)
                el.attrib["{%s}margin-top" % SNSD["fo"]] = \
                        el.attrib["{%s}margin-bottom" % SNSD["fo"]] = \
                        "%.3fpt" % (.1 * h)
            else:
                for subel in el.getchildren(): walk(subel)
        walk(root_el)

    def add_header_footer(self, root_el):
        automatic_styles = root_el.find(
            '{%s}automatic-styles' % SNSD['office'])
        path = '{%s}master-styles' % (NAME_SPACE_1, )
        master_el = root_el.find(path)
        if master_el is None:
            return
        path = '{%s}master-page' % (SNSD['style'], )
        master_el_container = master_el.findall(path)
        master_el = None
        target_attrib = '{%s}name' % (SNSD['style'], )
        target_name = self.rststyle('pagedefault')
        for el in master_el_container:
            if el.get(target_attrib) == target_name:
                master_el = el
                break
        if master_el is None:
            return
        el1 = master_el
        if self.header_content or self.settings.custom_header:
            if WhichElementTree == 'lxml':
                el2 = SubElement(el1, 'style:header', nsdict=SNSD)
            else:
                el2 = SubElement(el1, 'style:header',
                    attrib=STYLES_NAMESPACE_ATTRIB,
                    nsdict=STYLES_NAMESPACE_DICT,
                    )
            for el in self.header_content:
                attrkey = add_ns('text:style-name', nsdict=SNSD)
                el.attrib[attrkey] = self.rststyle('header')
                el2.append(el)
            if self.settings.custom_header:
                elcustom = self.create_custom_headfoot(el2,
                    self.settings.custom_header, 'header', automatic_styles)
        if self.footer_content or self.settings.custom_footer:
            if WhichElementTree == 'lxml':
                el2 = SubElement(el1, 'style:footer', nsdict=SNSD)
            else:
                el2 = SubElement(el1, 'style:footer',
                    attrib=STYLES_NAMESPACE_ATTRIB,
                    nsdict=STYLES_NAMESPACE_DICT,
                    )
            for el in self.footer_content:
                attrkey = add_ns('text:style-name', nsdict=SNSD)
                el.attrib[attrkey] = self.rststyle('footer')
                el2.append(el)
            if self.settings.custom_footer:
                elcustom = self.create_custom_headfoot(el2,
                    self.settings.custom_footer, 'footer', automatic_styles)

    code_none, code_field, code_text = range(3)
    field_pat = re.compile(r'%(..?)%')

    def create_custom_headfoot(self, parent, text, style_name, automatic_styles):
        parent = SubElement(parent, 'text:p', attrib={
            'text:style-name': self.rststyle(style_name),
            })
        current_element = None
        field_iter = self.split_field_specifiers_iter(text)
        for item in field_iter:
            if item[0] == ODFTranslator.code_field:
                if item[1] not in ('p', 'P', 
                    't1', 't2', 't3', 't4',
                    'd1', 'd2', 'd3', 'd4', 'd5',
                    's', 't', 'a'):
                    msg = 'bad field spec: %%%s%%' % (item[1], )
                    raise RuntimeError, msg
                el1 = self.make_field_element(parent,
                    item[1], style_name, automatic_styles)
                if el1 is None:
                    msg = 'bad field spec: %%%s%%' % (item[1], )
                    raise RuntimeError, msg
                else:
                    current_element = el1
            else:
                if current_element is None:
                    parent.text = item[1]
                else:
                    current_element.tail = item[1]

    def make_field_element(self, parent, text, style_name, automatic_styles):
        if text == 'p':
            el1 = SubElement(parent, 'text:page-number', attrib={
                #'text:style-name': self.rststyle(style_name),
                'text:select-page': 'current',
                })
        elif text == 'P':
            el1 = SubElement(parent, 'text:page-count', attrib={
                #'text:style-name': self.rststyle(style_name),
                })
        elif text == 't1':
            self.style_index += 1
            el1 = SubElement(parent, 'text:time', attrib={
                'text:style-name': self.rststyle(style_name),
                'text:fixed': 'true',
                'style:data-style-name': 'rst-time-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:time-style', attrib={
                'style:name': 'rst-time-style-%d' % self.style_index,
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:hours', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ':'
            el3 = SubElement(el2, 'number:minutes', attrib={
                    'number:style': 'long',
                    })
        elif text == 't2':
            self.style_index += 1
            el1 = SubElement(parent, 'text:time', attrib={
                'text:style-name': self.rststyle(style_name),
                'text:fixed': 'true',
                'style:data-style-name': 'rst-time-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:time-style', attrib={
                'style:name': 'rst-time-style-%d' % self.style_index,
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:hours', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ':'
            el3 = SubElement(el2, 'number:minutes', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ':'
            el3 = SubElement(el2, 'number:seconds', attrib={
                    'number:style': 'long',
                    })
        elif text == 't3':
            self.style_index += 1
            el1 = SubElement(parent, 'text:time', attrib={
                'text:style-name': self.rststyle(style_name),
                'text:fixed': 'true',
                'style:data-style-name': 'rst-time-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:time-style', attrib={
                'style:name': 'rst-time-style-%d' % self.style_index,
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:hours', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ':'
            el3 = SubElement(el2, 'number:minutes', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ' '
            el3 = SubElement(el2, 'number:am-pm')
        elif text == 't4':
            self.style_index += 1
            el1 = SubElement(parent, 'text:time', attrib={
                'text:style-name': self.rststyle(style_name),
                'text:fixed': 'true',
                'style:data-style-name': 'rst-time-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:time-style', attrib={
                'style:name': 'rst-time-style-%d' % self.style_index,
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:hours', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ':'
            el3 = SubElement(el2, 'number:minutes', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ':'
            el3 = SubElement(el2, 'number:seconds', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ' '
            el3 = SubElement(el2, 'number:am-pm')
        elif text == 'd1':
            self.style_index += 1
            el1 = SubElement(parent, 'text:date', attrib={
                'text:style-name': self.rststyle(style_name),
                'style:data-style-name': 'rst-date-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:date-style', attrib={
                'style:name': 'rst-date-style-%d' % self.style_index,
                'number:automatic-order': 'true',
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:month', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = '/'
            el3 = SubElement(el2, 'number:day', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = '/'
            el3 = SubElement(el2, 'number:year')
        elif text == 'd2':
            self.style_index += 1
            el1 = SubElement(parent, 'text:date', attrib={
                'text:style-name': self.rststyle(style_name),
                'style:data-style-name': 'rst-date-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:date-style', attrib={
                'style:name': 'rst-date-style-%d' % self.style_index,
                'number:automatic-order': 'true',
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:month', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = '/'
            el3 = SubElement(el2, 'number:day', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = '/'
            el3 = SubElement(el2, 'number:year', attrib={
                    'number:style': 'long',
                    })
        elif text == 'd3':
            self.style_index += 1
            el1 = SubElement(parent, 'text:date', attrib={
                'text:style-name': self.rststyle(style_name),
                'style:data-style-name': 'rst-date-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:date-style', attrib={
                'style:name': 'rst-date-style-%d' % self.style_index,
                'number:automatic-order': 'true',
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:month', attrib={
                    'number:textual': 'true',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ' '
            el3 = SubElement(el2, 'number:day', attrib={
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ', '
            el3 = SubElement(el2, 'number:year', attrib={
                    'number:style': 'long',
                    })
        elif text == 'd4':
            self.style_index += 1
            el1 = SubElement(parent, 'text:date', attrib={
                'text:style-name': self.rststyle(style_name),
                'style:data-style-name': 'rst-date-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:date-style', attrib={
                'style:name': 'rst-date-style-%d' % self.style_index,
                'number:automatic-order': 'true',
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:month', attrib={
                    'number:textual': 'true',
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ' '
            el3 = SubElement(el2, 'number:day', attrib={
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = ', '
            el3 = SubElement(el2, 'number:year', attrib={
                    'number:style': 'long',
                    })
        elif text == 'd5':
            self.style_index += 1
            el1 = SubElement(parent, 'text:date', attrib={
                'text:style-name': self.rststyle(style_name),
                'style:data-style-name': 'rst-date-style-%d' % self.style_index,
                })
            el2 = SubElement(automatic_styles, 'number:date-style', attrib={
                'style:name': 'rst-date-style-%d' % self.style_index,
                'xmlns:number': SNSD['number'],
                'xmlns:style': SNSD['style'],
                    })
            el3 = SubElement(el2, 'number:year', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = '-'
            el3 = SubElement(el2, 'number:month', attrib={
                    'number:style': 'long',
                    })
            el3 = SubElement(el2, 'number:text')
            el3.text = '-'
            el3 = SubElement(el2, 'number:day', attrib={
                    'number:style': 'long',
                    })
        elif text == 's':
            el1 = SubElement(parent, 'text:subject', attrib={
                'text:style-name': self.rststyle(style_name),
                })
        elif text == 't':
            el1 = SubElement(parent, 'text:title', attrib={
                'text:style-name': self.rststyle(style_name),
                })
        elif text == 'a':
            el1 = SubElement(parent, 'text:author-name', attrib={
                'text:fixed': 'false',
                })
        else:
            el1 = None
        return el1

    def split_field_specifiers_iter(self, text):
        pos1 = 0
        pos_end = len(text)
        while True:
            mo = ODFTranslator.field_pat.search(text, pos1)
            if mo:
                pos2 = mo.start()
                if pos2 > pos1:
                    yield (ODFTranslator.code_text, text[pos1:pos2])
                yield (ODFTranslator.code_field, mo.group(1))
                pos1 = mo.end()
            else:
                break
        trailing = text[pos1:]
        if trailing:
            yield (ODFTranslator.code_text, trailing)


    def astext(self):
        root = self.content_tree.getroot()
        et = etree.ElementTree(root)
        s1 = ToString(et)
        return s1

    def content_astext(self):
        return self.astext()

    def set_title(self, title): self.title = title
    def get_title(self): return self.title
    def set_embedded_file_list(self, embedded_file_list):
        self.embedded_file_list = embedded_file_list
    def get_embedded_file_list(self): return self.embedded_file_list
    def get_meta_dict(self): return self.meta_dict

    def process_footnotes(self):
        for node, el1 in self.footnote_list:
            backrefs = node.attributes.get('backrefs', [])
            first = True
            for ref in backrefs:
                el2 = self.footnote_ref_dict.get(ref)
                if el2 is not None:
                    if first:
                        first = False
                        el3 = copy.deepcopy(el1)
                        el2.append(el3)
                    else:
                        children = el2.getchildren()
                        if len(children) > 0: #  and 'id' in el2.attrib:
                            child = children[0]
                            ref1 = child.text
                            attribkey = add_ns('text:id', nsdict=SNSD)
                            id1 = el2.get(attribkey, 'footnote-error')
                            if id1 is None:
                                id1 = ''
                            tag = add_ns('text:note-ref', nsdict=SNSD)
                            el2.tag = tag
                            if self.settings.endnotes_end_doc:
                                note_class = 'endnote'
                            else:
                                note_class = 'footnote'
                            el2.attrib.clear()
                            attribkey = add_ns('text:note-class', nsdict=SNSD)
                            el2.attrib[attribkey] = note_class
                            attribkey = add_ns('text:ref-name', nsdict=SNSD)
                            el2.attrib[attribkey] = id1
                            attribkey = add_ns('text:reference-format', nsdict=SNSD)
                            el2.attrib[attribkey] = 'page'
                            el2.text = ref1

    #
    # Utility methods

    def append_child(self, tag, attrib=None, parent=None):
        if parent is None:
            parent = self.current_element
        if attrib is None:
            el = SubElement(parent, tag)
        else:
            el = SubElement(parent, tag, attrib)
        return el

    def append_p(self, style, text=None):
        result = self.append_child('text:p', attrib={
                'text:style-name': self.rststyle(style)})
        self.append_pending_ids(result)
        if text is not None:
            result.text = text
        return result

    def append_pending_ids(self, el):
        if self.settings.create_links:
            for id in self.pending_ids:
                SubElement(el, 'text:reference-mark', attrib={
                        'text:name': id})
        self.pending_ids = [ ]

    def set_current_element(self, el):
        self.current_element = el

    def set_to_parent(self):
        self.current_element = self.current_element.getparent()

    def generate_labeled_block(self, node, label):
        label = '%s:' % (self.language.labels[label], )
        el = self.append_p('textbody')
        el1 = SubElement(el, 'text:span',
            attrib={'text:style-name': self.rststyle('strong')})
        el1.text = label
        el = self.append_p('blockindent')
        return el

    def generate_labeled_line(self, node, label):
        label = '%s:' % (self.language.labels[label], )
        el = self.append_p('textbody')
        el1 = SubElement(el, 'text:span',
            attrib={'text:style-name': self.rststyle('strong')})
        el1.text = label
        el1.tail = node.astext()
        return el

    def encode(self, text):
        text = text.replace(u'\u00a0', " ")
        return text

    #
    # Visitor functions
    #
    # In alphabetic order, more or less.
    #   See docutils.docutils.nodes.node_class_names.
    #

    def dispatch_visit(self, node):
        """Override to catch basic attributes which many nodes have."""
        self.handle_basic_atts(node)
        nodes.GenericNodeVisitor.dispatch_visit(self, node)

    def handle_basic_atts(self, node):
        if isinstance(node, nodes.Element) and node['ids']:
            self.pending_ids += node['ids']

    def default_visit(self, node):
        self.document.reporter.warning('missing visit_%s' % (node.tagname, ))

    def default_departure(self, node):
        self.document.reporter.warning('missing depart_%s' % (node.tagname, ))

    def visit_Text(self, node):
        # Skip nodes whose text has been processed in parent nodes.
        if isinstance(node.parent, docutils.nodes.literal_block):
            return
        text = node.astext()
        # Are we in mixed content?  If so, add the text to the
        #   etree tail of the previous sibling element.
        if len(self.current_element.getchildren()) > 0:
            if self.current_element.getchildren()[-1].tail:
                self.current_element.getchildren()[-1].tail += text
            else:
                self.current_element.getchildren()[-1].tail = text
        else:
            if self.current_element.text:
                self.current_element.text += text
            else:
                self.current_element.text = text

    def depart_Text(self, node):
        pass

    #
    # Pre-defined fields
    #

    def visit_address(self, node):
        el = self.generate_labeled_block(node, 'address')
        self.set_current_element(el)

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

    def visit_author(self, node):
        if isinstance(node.parent, nodes.authors):
            el = self.append_p('blockindent')
        else:
            el = self.generate_labeled_block(node, 'author')
        self.set_current_element(el)

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

    def visit_authors(self, node):
        label = '%s:' % (self.language.labels['authors'], )
        el = self.append_p('textbody')
        el1 = SubElement(el, 'text:span',
            attrib={'text:style-name': self.rststyle('strong')})
        el1.text = label

    def depart_authors(self, node):
        pass

    def visit_contact(self, node):
        el = self.generate_labeled_block(node, 'contact')
        self.set_current_element(el)

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

    def visit_copyright(self, node):
        el = self.generate_labeled_block(node, 'copyright')
        self.set_current_element(el)

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

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

    def depart_date(self, node):
        pass

    def visit_organization(self, node):
        el = self.generate_labeled_block(node, 'organization')
        self.set_current_element(el)

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

    def visit_status(self, node):
        el = self.generate_labeled_block(node, 'status')
        self.set_current_element(el)

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

    def visit_revision(self, node):
        el = self.generate_labeled_line(node, 'revision')

    def depart_revision(self, node):
        pass

    def visit_version(self, node):
        el = self.generate_labeled_line(node, 'version')
        #self.set_current_element(el)

    def depart_version(self, node):
        #self.set_to_parent()
        pass

    def visit_attribution(self, node):
        el = self.append_p('attribution', node.astext())

    def depart_attribution(self, node):
        pass

    def visit_block_quote(self, node):
        if 'epigraph' in node.attributes['classes']:
            self.paragraph_style_stack.append(self.rststyle('epigraph'))
            self.blockstyle = self.rststyle('epigraph')
        elif 'highlights' in node.attributes['classes']:
            self.paragraph_style_stack.append(self.rststyle('highlights'))
            self.blockstyle = self.rststyle('highlights')
        else:
            self.paragraph_style_stack.append(self.rststyle('blockquote'))
            self.blockstyle = self.rststyle('blockquote')
        self.line_indent_level += 1

    def depart_block_quote(self, node):
        self.paragraph_style_stack.pop()
        self.blockstyle = ''
        self.line_indent_level -= 1

    def visit_bullet_list(self, node):
        self.list_level +=1
        if self.in_table_of_contents:
            if self.settings.generate_oowriter_toc:
                pass
            else:
                if node.has_key('classes') and \
                        'auto-toc' in node.attributes['classes']:
                    el = SubElement(self.current_element, 'text:list', attrib={
                        'text:style-name': self.rststyle('tocenumlist'),
                        })
                    self.list_style_stack.append(self.rststyle('enumitem'))
                else:
                    el = SubElement(self.current_element, 'text:list', attrib={
                        'text:style-name': self.rststyle('tocbulletlist'),
                        })
                    self.list_style_stack.append(self.rststyle('bulletitem'))
                self.set_current_element(el)
        else:
            if self.blockstyle == self.rststyle('blockquote'):
                el = SubElement(self.current_element, 'text:list', attrib={
                    'text:style-name': self.rststyle('blockquote-bulletlist'),
                    })
                self.list_style_stack.append(
                    self.rststyle('blockquote-bulletitem'))
            elif self.blockstyle == self.rststyle('highlights'):
                el = SubElement(self.current_element, 'text:list', attrib={
                    'text:style-name': self.rststyle('highlights-bulletlist'),
                    })
                self.list_style_stack.append(
                    self.rststyle('highlights-bulletitem'))
            elif self.blockstyle == self.rststyle('epigraph'):
                el = SubElement(self.current_element, 'text:list', attrib={
                    'text:style-name': self.rststyle('epigraph-bulletlist'),
                    })
                self.list_style_stack.append(
                    self.rststyle('epigraph-bulletitem'))
            else:
                el = SubElement(self.current_element, 'text:list', attrib={
                    'text:style-name': self.rststyle('bulletlist'),
                    })
                self.list_style_stack.append(self.rststyle('bulletitem'))
            self.set_current_element(el)

    def depart_bullet_list(self, node):
        if self.in_table_of_contents:
            if self.settings.generate_oowriter_toc:
                pass
            else:
                self.set_to_parent()
                self.list_style_stack.pop()
        else:
            self.set_to_parent()
            self.list_style_stack.pop()
        self.list_level -=1

    def visit_caption(self, node):
        raise nodes.SkipChildren()
        pass

    def depart_caption(self, node):
        pass

    def visit_comment(self, node):
        el = self.append_p('textbody')
        el1 =  SubElement(el, 'office:annotation', attrib={})
        el2 =  SubElement(el1, 'dc:creator', attrib={})
        s1 = os.environ.get('USER', '')
        el2.text = s1
        el2 =  SubElement(el1, 'text:p', attrib={})
        el2.text = node.astext()

    def depart_comment(self, node):
        pass

    def visit_compound(self, node):
        # The compound directive currently receives no special treatment.
        pass

    def depart_compound(self, node):
        pass

    def visit_container(self, node):
        styles = node.attributes.get('classes', ())
        if len(styles) > 0:
            self.paragraph_style_stack.append(self.rststyle(styles[0]))

    def depart_container(self, node):
        styles = node.attributes.get('classes', ())
        if len(styles) > 0:
            self.paragraph_style_stack.pop()

    def visit_decoration(self, node):
        pass

    def depart_decoration(self, node):
        pass

    def visit_definition_list(self, node):
        self.def_list_level +=1
        if self.list_level > 5:
            raise RuntimeError(
                'max definition list nesting level exceeded')

    def depart_definition_list(self, node):
        self.def_list_level -=1

    def visit_definition_list_item(self, node):
        pass

    def depart_definition_list_item(self, node):
        pass

    def visit_term(self, node):
        el = self.append_p('deflist-term-%d' % self.def_list_level)
        el.text = node.astext()
        self.set_current_element(el)
        raise nodes.SkipChildren()

    def depart_term(self, node):
        self.set_to_parent()

    def visit_definition(self, node):
        self.paragraph_style_stack.append(
            self.rststyle('deflist-def-%d' % self.def_list_level))
        self.bumped_list_level_stack.append(ListLevel(1))

    def depart_definition(self, node):
        self.paragraph_style_stack.pop()
        self.bumped_list_level_stack.pop()

    def visit_classifier(self, node):
        els = self.current_element.getchildren()
        if len(els) > 0:
            el = els[-1]
            el1 = SubElement(el, 'text:span',
                attrib={'text:style-name': self.rststyle('emphasis')
                })
            el1.text = ' (%s)' % (node.astext(), )

    def depart_classifier(self, node):
        pass

    def visit_document(self, node):
        pass

    def depart_document(self, node):
        self.process_footnotes()

    def visit_docinfo(self, node):
        self.section_level += 1
        self.section_count += 1
        if self.settings.create_sections:
            el = self.append_child('text:section', attrib={
                    'text:name': 'Section%d' % self.section_count,
                    'text:style-name': 'Sect%d' % self.section_level,
                    })
            self.set_current_element(el)

    def depart_docinfo(self, node):
        self.section_level -= 1
        if self.settings.create_sections:
            self.set_to_parent()

    def visit_emphasis(self, node):
        el = SubElement(self.current_element, 'text:span',
            attrib={'text:style-name': self.rststyle('emphasis')})
        self.set_current_element(el)

    def depart_emphasis(self, node):
        self.set_to_parent()

    def visit_enumerated_list(self, node):
        el1 = self.current_element
        if self.blockstyle == self.rststyle('blockquote'):
            el2 = SubElement(el1, 'text:list', attrib={
                'text:style-name': self.rststyle('blockquote-enumlist'),
                })
            self.list_style_stack.append(self.rststyle('blockquote-enumitem'))
        elif self.blockstyle == self.rststyle('highlights'):
            el2 = SubElement(el1, 'text:list', attrib={
                'text:style-name': self.rststyle('highlights-enumlist'),
                })
            self.list_style_stack.append(self.rststyle('highlights-enumitem'))
        elif self.blockstyle == self.rststyle('epigraph'):
            el2 = SubElement(el1, 'text:list', attrib={
                'text:style-name': self.rststyle('epigraph-enumlist'),
                })
            self.list_style_stack.append(self.rststyle('epigraph-enumitem'))
        else:
            liststylename = 'enumlist-%s' % (node.get('enumtype', 'arabic'), )
            el2 = SubElement(el1, 'text:list', attrib={
                'text:style-name': self.rststyle(liststylename),
                })
            self.list_style_stack.append(self.rststyle('enumitem'))
        self.set_current_element(el2)

    def depart_enumerated_list(self, node):
        self.set_to_parent()
        self.list_style_stack.pop()

    def visit_list_item(self, node):
        # If we are in a "bumped" list level, then wrap this
        #   list in an outer lists in order to increase the
        #   indentation level.
        if self.in_table_of_contents:
            if self.settings.generate_oowriter_toc:
                self.paragraph_style_stack.append(
                    self.rststyle('contents-%d' % (self.list_level, )))
            else:
                el1 = self.append_child('text:list-item')
                self.set_current_element(el1)
        else:
            el1 = self.append_child('text:list-item')
            el3 = el1
            if len(self.bumped_list_level_stack) > 0:
                level_obj = self.bumped_list_level_stack[-1]
                if level_obj.get_sibling():
                    level_obj.set_nested(False)
                    for level_obj1 in self.bumped_list_level_stack:
                        for idx in range(level_obj1.get_level()):
                            el2 = self.append_child('text:list', parent=el3)
                            el3 = self.append_child(
                                'text:list-item', parent=el2)
            self.paragraph_style_stack.append(self.list_style_stack[-1])
            self.set_current_element(el3)

    def depart_list_item(self, node):
        if self.in_table_of_contents:
            if self.settings.generate_oowriter_toc:
                self.paragraph_style_stack.pop()
            else:
                self.set_to_parent()
        else:
            if len(self.bumped_list_level_stack) > 0:
                level_obj = self.bumped_list_level_stack[-1]
                if level_obj.get_sibling():
                    level_obj.set_nested(True)
                    for level_obj1 in self.bumped_list_level_stack:
                        for idx in range(level_obj1.get_level()):
                            self.set_to_parent()
                            self.set_to_parent()
            self.paragraph_style_stack.pop()
            self.set_to_parent()

    def visit_header(self, node):
        self.in_header = True

    def depart_header(self, node):
        self.in_header = False

    def visit_footer(self, node):
        self.in_footer = True

    def depart_footer(self, node):
        self.in_footer = False

    def visit_field(self, node):
        pass

    def depart_field(self, node):
        pass

    def visit_field_list(self, node):
        pass

    def depart_field_list(self, node):
        pass

    def visit_field_name(self, node):
        el = self.append_p('textbody')
        el1 = SubElement(el, 'text:span',
            attrib={'text:style-name': self.rststyle('strong')})
        el1.text = node.astext()

    def depart_field_name(self, node):
        pass

    def visit_field_body(self, node):
        self.paragraph_style_stack.append(self.rststyle('blockindent'))

    def depart_field_body(self, node):
        self.paragraph_style_stack.pop()

    def visit_figure(self, node):
        pass

    def depart_figure(self, node):
        pass

    def visit_footnote(self, node):
        self.footnote_level += 1
        self.save_footnote_current = self.current_element
        el1 = Element('text:note-body')
        self.current_element = el1
        self.footnote_list.append((node, el1))
        if isinstance(node, docutils.nodes.citation):
            self.paragraph_style_stack.append(self.rststyle('citation'))
        else:
            self.paragraph_style_stack.append(self.rststyle('footnote'))

    def depart_footnote(self, node):
        self.paragraph_style_stack.pop()
        self.current_element = self.save_footnote_current
        self.footnote_level -= 1

    footnote_chars = [
        '*', '**', '***',
        '++', '+++',
        '##', '###',
        '@@', '@@@',
        ]

    def visit_footnote_reference(self, node):
        if self.footnote_level <= 0:
            id = node.attributes['ids'][0]
            refid = node.attributes.get('refid')
            if refid is None:
                refid = ''
            if self.settings.endnotes_end_doc:
                note_class = 'endnote'
            else:
                note_class = 'footnote'
            el1 = self.append_child('text:note', attrib={
                'text:id': '%s' % (refid, ),
                'text:note-class': note_class,
                })
            note_auto = str(node.attributes.get('auto', 1))
            if isinstance(node, docutils.nodes.citation_reference):
                citation = '[%s]' % node.astext()
                el2 = SubElement(el1, 'text:note-citation', attrib={
                    'text:label': citation,
                    })
                el2.text = citation
            elif note_auto == '1':
                el2 = SubElement(el1, 'text:note-citation', attrib={
                    'text:label': node.astext(),
                    })
                el2.text = node.astext()
            elif note_auto == '*':
                if self.footnote_chars_idx >= len(
                    ODFTranslator.footnote_chars):
                    self.footnote_chars_idx = 0
                footnote_char = ODFTranslator.footnote_chars[
                    self.footnote_chars_idx]
                self.footnote_chars_idx += 1
                el2 = SubElement(el1, 'text:note-citation', attrib={
                    'text:label': footnote_char,
                    })
                el2.text = footnote_char
            self.footnote_ref_dict[id] = el1
        raise nodes.SkipChildren()

    def depart_footnote_reference(self, node):
        pass

    def visit_citation(self, node):
        self.in_citation = True
        for id in node.attributes['ids']:
            self.citation_id = id
            break
        self.paragraph_style_stack.append(self.rststyle('blockindent'))
        self.bumped_list_level_stack.append(ListLevel(1))

    def depart_citation(self, node):
        self.citation_id = None
        self.paragraph_style_stack.pop()
        self.bumped_list_level_stack.pop()
        self.in_citation = False

    def visit_citation_reference(self, node):
        if self.settings.create_links:
            id = node.attributes['refid']
            el = self.append_child('text:reference-ref', attrib={
                'text:ref-name': '%s' % (id, ),
                'text:reference-format': 'text',
                })
            el.text = '['
            self.set_current_element(el)
        elif self.current_element.text is None:
            self.current_element.text = '['
        else:
            self.current_element.text += '['

    def depart_citation_reference(self, node):
        self.current_element.text += ']'
        if self.settings.create_links:
            self.set_to_parent()

    def visit_label(self, node):
        if isinstance(node.parent, docutils.nodes.footnote):
            raise nodes.SkipChildren()
        elif self.citation_id is not None:
            el = self.append_p('textbody')
            self.set_current_element(el)
            if self.settings.create_links:
                el0 = SubElement(el, 'text:span')
                el0.text = '['
                el1 = self.append_child('text:reference-mark-start', attrib={
                        'text:name': '%s' % (self.citation_id, ),
                        })
            else:
                el.text = '['

    def depart_label(self, node):
        if isinstance(node.parent, docutils.nodes.footnote):
            pass
        elif self.citation_id is not None:
            if self.settings.create_links:
                el = self.append_child('text:reference-mark-end', attrib={
                        'text:name': '%s' % (self.citation_id, ),
                        })
                el0 = SubElement(self.current_element, 'text:span')
                el0.text = ']'
            else:
                self.current_element.text += ']'
            self.set_to_parent()

    def visit_generated(self, node):
        pass

    def depart_generated(self, node):
        pass

    def check_file_exists(self, path):
        if os.path.exists(path):
            return 1
        else:
            return 0

    def visit_image(self, node):
        # Capture the image file.
        if 'uri' in node.attributes:
            source = node.attributes['uri']
            if not source.startswith('http:'):
                if not source.startswith(os.sep):
                    docsource, line = utils.get_source_line(node)
                    if docsource:
                        dirname = os.path.dirname(docsource)
                        if dirname:
                            source = '%s%s%s' % (dirname, os.sep, source, )
                if not self.check_file_exists(source):
                    self.document.reporter.warning(
                        'Cannot find image file %s.' % (source, ))
                    return
        else:
            return
        if source in self.image_dict:
            filename, destination = self.image_dict[source]
        else:
            self.image_count += 1
            filename = os.path.split(source)[1]
            destination = 'Pictures/1%08x_%s' % (self.image_count,
			    filename.encode("ascii", "ignore"))
            if source.startswith('http:'):
                try:
                    imgfile = urllib2.urlopen(source)
                    content = imgfile.read()
                    imgfile.close()
                    imgfile2 = tempfile.NamedTemporaryFile('wb', delete=False)
                    imgfile2.write(content)
                    imgfile2.close()
                    imgfilename = imgfile2.name
                    source = imgfilename
                except urllib2.HTTPError, e:
                    self.document.reporter.warning(
                        "Can't open image url %s." % (source, ))
                spec = (source, destination,)
            else:
                spec = (os.path.abspath(source), destination,)
            self.embedded_file_list.append(spec)
            self.image_dict[source] = (source, destination,)
        # Is this a figure (containing an image) or just a plain image?
        if self.in_paragraph:
            el1 = self.current_element
        else:
            el1 = SubElement(self.current_element, 'text:p',
                attrib={'text:style-name': self.rststyle('textbody')})
        el2 = el1
        if isinstance(node.parent, docutils.nodes.figure):
            el3, el4, el5, caption = self.generate_figure(node, source,
                destination, el2)
            attrib = {}
            el6, width = self.generate_image(node, source, destination,
                el5, attrib)
            if caption is not None:
                el6.tail = caption
        else:   #if isinstance(node.parent, docutils.nodes.image):
            el3 = self.generate_image(node, source, destination, el2)

    def depart_image(self, node):
        pass

    def get_image_width_height(self, node, attr):
        size = None
        if attr in node.attributes:
            size = node.attributes[attr]
            unit = size[-2:]
            if unit.isalpha():
                size = size[:-2]
            else:
                unit = 'px'
            try:
                size = float(size)
            except ValueError, e:
                self.document.reporter.warning(
                    'Invalid %s for image: "%s"' % (
                        attr, node.attributes[attr]))
            size = [size, unit]
        return size

    def get_image_scale(self, node):
        if 'scale' in node.attributes:
            try:
                scale = int(node.attributes['scale'])
                if scale < 1: # or scale > 100:
                    self.document.reporter.warning(
                        'scale out of range (%s), using 1.' % (scale, ))
                    scale = 1
                scale = scale * 0.01
            except ValueError, e:
                self.document.reporter.warning(
                    'Invalid scale for image: "%s"' % (
                        node.attributes['scale'], ))
        else:
            scale = 1.0
        return scale

    def get_image_scaled_width_height(self, node, source):
        scale = self.get_image_scale(node)
        width = self.get_image_width_height(node, 'width')
        height = self.get_image_width_height(node, 'height')

        dpi = (72, 72)
        if PIL is not None and source in self.image_dict:
            filename, destination = self.image_dict[source]
            imageobj = PIL.Image.open(filename, 'r')
            dpi = imageobj.info.get('dpi', dpi)
            # dpi information can be (xdpi, ydpi) or xydpi
            try: iter(dpi)
            except: dpi = (dpi, dpi)
        else:
            imageobj = None

        if width is None or height is None:
            if imageobj is None:
                raise RuntimeError(
                    'image size not fully specified and PIL not installed')
            if width is None: width = [imageobj.size[0], 'px']
            if height is None: height = [imageobj.size[1], 'px']

        width[0] *= scale
        height[0] *= scale
        if width[1] == 'px': width = [width[0] / dpi[0], 'in']
        if height[1] == 'px': height = [height[0] / dpi[1], 'in']

        width[0] = str(width[0])
        height[0] = str(height[0])
        return ''.join(width), ''.join(height)

    def generate_figure(self, node, source, destination, current_element):
        caption = None
        width, height = self.get_image_scaled_width_height(node, source)
        for node1 in node.parent.children:
            if node1.tagname == 'caption':
                caption = node1.astext()
        self.image_style_count += 1
        #
        # Add the style for the caption.
        if caption is not None:
            attrib = {
                'style:class': 'extra',
                'style:family': 'paragraph',
                'style:name': 'Caption',
                'style:parent-style-name': 'Standard',
                }
            el1 = SubElement(self.automatic_styles, 'style:style',
                attrib=attrib, nsdict=SNSD)
            attrib = {
                'fo:margin-bottom': '0.0835in',
                'fo:margin-top': '0.0835in',
                'text:line-number': '0',
                'text:number-lines': 'false',
                }
            el2 = SubElement(el1, 'style:paragraph-properties', 
                attrib=attrib, nsdict=SNSD)
            attrib = {
                'fo:font-size': '12pt',
                'fo:font-style': 'italic',
                'style:font-name': 'Times',
                'style:font-name-complex': 'Lucidasans1',
                'style:font-size-asian': '12pt',
                'style:font-size-complex': '12pt',
                'style:font-style-asian': 'italic',
                'style:font-style-complex': 'italic',
                }
            el2 = SubElement(el1, 'style:text-properties', 
                attrib=attrib, nsdict=SNSD)
        style_name = 'rstframestyle%d' % self.image_style_count
        # Add the styles
        attrib = {
            'style:name': style_name,
            'style:family': 'graphic',
            'style:parent-style-name': self.rststyle('figureframe'),
            }
        el1 = SubElement(self.automatic_styles, 
            'style:style', attrib=attrib, nsdict=SNSD)
        halign = 'center'
        valign = 'top'
        if 'align' in node.attributes:
            align = node.attributes['align'].split()
            for val in align:
                if val in ('left', 'center', 'right'):
                    halign = val
                elif val in ('top', 'middle', 'bottom'):
                    valign = val
        attrib = {}
        wrap = False
        classes = node.parent.attributes.get('classes')
        if classes and 'wrap' in classes:
            wrap = True
        if wrap:
            attrib['style:wrap'] = 'dynamic'
        else:
            attrib['style:wrap'] = 'none'
        el2 = SubElement(el1,
            'style:graphic-properties', attrib=attrib, nsdict=SNSD)
        attrib = {
            'draw:style-name': style_name,
            'draw:name': 'Frame1',
            'text:anchor-type': 'paragraph',
            'draw:z-index': '0',
            }
        attrib['svg:width'] = width
        el3 = SubElement(current_element, 'draw:frame', attrib=attrib)
        attrib = {}
        el4 = SubElement(el3, 'draw:text-box', attrib=attrib)
        attrib = {
            'text:style-name': self.rststyle('caption'),
            }
        el5 = SubElement(el4, 'text:p', attrib=attrib)
        return el3, el4, el5, caption

    def generate_image(self, node, source, destination, current_element,
        frame_attrs=None):
        width, height = self.get_image_scaled_width_height(node, source)
        self.image_style_count += 1
        style_name = 'rstframestyle%d' % self.image_style_count
        # Add the style.
        attrib = {
            'style:name': style_name,
            'style:family': 'graphic',
            'style:parent-style-name': self.rststyle('image'),
            }
        el1 = SubElement(self.automatic_styles, 
            'style:style', attrib=attrib, nsdict=SNSD)
        halign = None
        valign = None
        if 'align' in node.attributes:
            align = node.attributes['align'].split()
            for val in align:
                if val in ('left', 'center', 'right'):
                    halign = val
                elif val in ('top', 'middle', 'bottom'):
                    valign = val
        if frame_attrs is None:
            attrib = {
                'style:vertical-pos': 'top',
                'style:vertical-rel': 'paragraph',
                'style:horizontal-rel': 'paragraph',
                'style:mirror': 'none',
                'fo:clip': 'rect(0cm 0cm 0cm 0cm)',
                'draw:luminance': '0%',
                'draw:contrast': '0%',
                'draw:red': '0%',
                'draw:green': '0%',
                'draw:blue': '0%',
                'draw:gamma': '100%',
                'draw:color-inversion': 'false',
                'draw:image-opacity': '100%',
                'draw:color-mode': 'standard',
                }
        else:
            attrib = frame_attrs
        if halign is not None:
            attrib['style:horizontal-pos'] = halign
        if valign is not None:
            attrib['style:vertical-pos'] = valign
        # If there is a classes/wrap directive or we are 
        #   inside a table, add a no-wrap style.
        wrap = False
        classes = node.attributes.get('classes')
        if classes and 'wrap' in classes:
            wrap = True
        if wrap:
            attrib['style:wrap'] = 'dynamic'
        else:
            attrib['style:wrap'] = 'none'
        # If we are inside a table, add a no-wrap style.
        if self.is_in_table(node):
            attrib['style:wrap'] = 'none'
        el2 = SubElement(el1,
            'style:graphic-properties', attrib=attrib, nsdict=SNSD)
        # Add the content.
        #el = SubElement(current_element, 'text:p',
        #    attrib={'text:style-name': self.rststyle('textbody')})
        attrib={
            'draw:style-name': style_name,
            'draw:name': 'graphics2',
            'draw:z-index': '1',
            }
        if isinstance(node.parent, nodes.TextElement):
            attrib['text:anchor-type'] = 'as-char' #vds
        else:
            attrib['text:anchor-type'] = 'paragraph'
        attrib['svg:width'] = width
        attrib['svg:height'] = height
        el1 = SubElement(current_element, 'draw:frame', attrib=attrib)
        el2 = SubElement(el1, 'draw:image', attrib={
            'xlink:href': '%s' % (destination, ),
            'xlink:type': 'simple',
            'xlink:show': 'embed',
            'xlink:actuate': 'onLoad',
            })
        return el1, width

    def is_in_table(self, node):
        node1 = node.parent
        while node1:
            if isinstance(node1, docutils.nodes.entry):
                return True
            node1 = node1.parent
        return False

    def visit_legend(self, node):
        if isinstance(node.parent, docutils.nodes.figure):
            el1 = self.current_element[-1]
            el1 = el1[0][0]
            self.current_element = el1
            self.paragraph_style_stack.append(self.rststyle('legend'))

    def depart_legend(self, node):
        if isinstance(node.parent, docutils.nodes.figure):
            self.paragraph_style_stack.pop()
            self.set_to_parent()
            self.set_to_parent()
            self.set_to_parent()

    def visit_line_block(self, node):
        self.line_indent_level += 1
        self.line_block_level += 1

    def depart_line_block(self, node):
        self.line_indent_level -= 1
        self.line_block_level -= 1

    def visit_line(self, node):
        style = 'lineblock%d' % self.line_indent_level
        el1 = SubElement(self.current_element, 'text:p', attrib={
                'text:style-name': self.rststyle(style),
                })
        self.current_element = el1

    def depart_line(self, node):
        self.set_to_parent()

    def visit_literal(self, node):
        el = SubElement(self.current_element, 'text:span',
            attrib={'text:style-name': self.rststyle('inlineliteral')})
        self.set_current_element(el)

    def depart_literal(self, node):
        self.set_to_parent()

    def visit_inline(self, node):
        styles = node.attributes.get('classes', ())
        if len(styles) > 0:
            inline_style =  styles[0]
        el = SubElement(self.current_element, 'text:span',
            attrib={'text:style-name': self.rststyle(inline_style)})
        self.set_current_element(el)

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

    def _calculate_code_block_padding(self, line):
        count = 0
        matchobj = SPACES_PATTERN.match(line)
        if matchobj:
            pad = matchobj.group()
            count = len(pad)
        else:
            matchobj = TABS_PATTERN.match(line)
            if matchobj:
                pad = matchobj.group()
                count = len(pad) * 8
        return count

    def _add_syntax_highlighting(self, insource, language):
        lexer = pygments.lexers.get_lexer_by_name(language, stripall=True)
        if language in ('latex', 'tex'):
            fmtr = OdtPygmentsLaTeXFormatter(lambda name, parameters=():
                self.rststyle(name, parameters),
                escape_function=escape_cdata)
        else:
            fmtr = OdtPygmentsProgFormatter(lambda name, parameters=():
                self.rststyle(name, parameters),
                escape_function=escape_cdata)
        outsource = pygments.highlight(insource, lexer, fmtr)
        return outsource

    def fill_line(self, line):
        line = FILL_PAT1.sub(self.fill_func1, line)
        line = FILL_PAT2.sub(self.fill_func2, line)
        return line

    def fill_func1(self, matchobj):
        spaces = matchobj.group(0)
        repl = '<text:s text:c="%d"/>' % (len(spaces), )
        return repl

    def fill_func2(self, matchobj):
        spaces = matchobj.group(0)
        repl = ' <text:s text:c="%d"/>' % (len(spaces) - 1, )
        return repl

    def visit_literal_block(self, node):
        if len(self.paragraph_style_stack) > 1:
            wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
                self.rststyle('codeblock-indented'), )
        else:
            wrapper1 = '<text:p text:style-name="%s">%%s</text:p>' % (
                self.rststyle('codeblock'), )
        source = node.astext()
        if (pygments and
            self.settings.add_syntax_highlighting
            #and
            #node.get('hilight', False)
            ):
            language = node.get('language', 'python')
            source = self._add_syntax_highlighting(source, language)
        else:
            source = escape_cdata(source)
        lines = source.split('\n')
        # If there is an empty last line, remove it.
        if lines[-1] == '':
            del lines[-1]
        lines1 = ['<wrappertag1 xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">']

        my_lines = []
        for my_line in lines:
            my_line = self.fill_line(my_line)
            my_line = my_line.replace("&#10;", "\n")
            my_lines.append(my_line)
        my_lines_str = '<text:line-break/>'.join(my_lines)
        my_lines_str2 = wrapper1 % (my_lines_str, )
        lines1.append(my_lines_str2)
        lines1.append('</wrappertag1>')
        s1 = ''.join(lines1)
        if WhichElementTree != "lxml":
            s1 = s1.encode("utf-8")
        el1 = etree.fromstring(s1)
        children = el1.getchildren()
        for child in children:
            self.current_element.append(child)

    def depart_literal_block(self, node):
        pass

    visit_doctest_block = visit_literal_block
    depart_doctest_block = depart_literal_block

    # placeholder for math (see docs/dev/todo.txt)
    def visit_math(self, node):
        self.document.reporter.warning('"math" role not supported',
                base_node=node)
        self.visit_literal(node)

    def depart_math(self, node):
        self.depart_literal(node)

    def visit_math_block(self, node):
        self.document.reporter.warning('"math" directive not supported',
                base_node=node)
        self.visit_literal_block(node)

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

    def visit_meta(self, node):
        name = node.attributes.get('name')
        content = node.attributes.get('content')
        if name is not None and content is not None:
            self.meta_dict[name] = content

    def depart_meta(self, node):
        pass

    def visit_option_list(self, node):
        table_name = 'tableoption'
        #
        # Generate automatic styles
        if not self.optiontablestyles_generated:
            self.optiontablestyles_generated = True
            el = SubElement(self.automatic_styles, 'style:style', attrib={
                'style:name': self.rststyle(table_name),
                'style:family': 'table'}, nsdict=SNSD)
            el1 = SubElement(el, 'style:table-properties', attrib={
                'style:width': '17.59cm',
                'table:align': 'left',
                'style:shadow': 'none'}, nsdict=SNSD)
            el = SubElement(self.automatic_styles, 'style:style', attrib={
                'style:name': self.rststyle('%s.%%c' % table_name, ( 'A', )),
                'style:family': 'table-column'}, nsdict=SNSD)
            el1 = SubElement(el, 'style:table-column-properties', attrib={
                'style:column-width': '4.999cm'}, nsdict=SNSD)
            el = SubElement(self.automatic_styles, 'style:style', attrib={
                'style:name': self.rststyle('%s.%%c' % table_name, ( 'B', )),
                'style:family': 'table-column'}, nsdict=SNSD)
            el1 = SubElement(el, 'style:table-column-properties', attrib={
                'style:column-width': '12.587cm'}, nsdict=SNSD)
            el = SubElement(self.automatic_styles, 'style:style', attrib={
                'style:name': self.rststyle(
                    '%s.%%c%%d' % table_name, ( 'A', 1, )),
                'style:family': 'table-cell'}, nsdict=SNSD)
            el1 = SubElement(el, 'style:table-cell-properties', attrib={
                'fo:background-color': 'transparent',
                'fo:padding': '0.097cm',
                'fo:border-left': '0.035cm solid #000000',
                'fo:border-right': 'none',
                'fo:border-top': '0.035cm solid #000000',
                'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
            el2 = SubElement(el1, 'style:background-image', nsdict=SNSD)
            el = SubElement(self.automatic_styles, 'style:style', attrib={
                'style:name': self.rststyle(
                    '%s.%%c%%d' % table_name, ( 'B', 1, )),
                'style:family': 'table-cell'}, nsdict=SNSD)
            el1 = SubElement(el, 'style:table-cell-properties', attrib={
                'fo:padding': '0.097cm',
                'fo:border': '0.035cm solid #000000'}, nsdict=SNSD)
            el = SubElement(self.automatic_styles, 'style:style', attrib={
                'style:name': self.rststyle(
                    '%s.%%c%%d' % table_name, ( 'A', 2, )),
                'style:family': 'table-cell'}, nsdict=SNSD)
            el1 = SubElement(el, 'style:table-cell-properties', attrib={
                'fo:padding': '0.097cm',
                'fo:border-left': '0.035cm solid #000000',
                'fo:border-right': 'none',
                'fo:border-top': 'none',
                'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
            el = SubElement(self.automatic_styles, 'style:style', attrib={
                'style:name': self.rststyle(
                    '%s.%%c%%d' % table_name, ( 'B', 2, )),
                'style:family': 'table-cell'}, nsdict=SNSD)
            el1 = SubElement(el, 'style:table-cell-properties', attrib={
                'fo:padding': '0.097cm',
                'fo:border-left': '0.035cm solid #000000',
                'fo:border-right': '0.035cm solid #000000',
                'fo:border-top': 'none',
                'fo:border-bottom': '0.035cm solid #000000'}, nsdict=SNSD)
        #
        # Generate table data
        el = self.append_child('table:table', attrib={
            'table:name': self.rststyle(table_name),
            'table:style-name': self.rststyle(table_name),
            })
        el1 = SubElement(el, 'table:table-column', attrib={
            'table:style-name': self.rststyle(
                '%s.%%c' % table_name, ( 'A', ))})
        el1 = SubElement(el, 'table:table-column', attrib={
            'table:style-name': self.rststyle(
                '%s.%%c' % table_name, ( 'B', ))})
        el1 = SubElement(el, 'table:table-header-rows')
        el2 = SubElement(el1, 'table:table-row')
        el3 = SubElement(el2, 'table:table-cell', attrib={
            'table:style-name': self.rststyle(
                '%s.%%c%%d' % table_name, ( 'A', 1, )),
            'office:value-type': 'string'})
        el4 = SubElement(el3, 'text:p', attrib={
            'text:style-name': 'Table_20_Heading'})
        el4.text= 'Option'
        el3 = SubElement(el2, 'table:table-cell', attrib={
            'table:style-name': self.rststyle(
                '%s.%%c%%d' % table_name, ( 'B', 1, )),
            'office:value-type': 'string'})
        el4 = SubElement(el3, 'text:p', attrib={
            'text:style-name': 'Table_20_Heading'})
        el4.text= 'Description'
        self.set_current_element(el)

    def depart_option_list(self, node):
        self.set_to_parent()

    def visit_option_list_item(self, node):
        el = self.append_child('table:table-row')
        self.set_current_element(el)

    def depart_option_list_item(self, node):
        self.set_to_parent()

    def visit_option_group(self, node):
        el = self.append_child('table:table-cell', attrib={
            'table:style-name': 'Table%d.A2' % self.table_count,
            'office:value-type': 'string',
        })
        self.set_current_element(el)

    def depart_option_group(self, node):
        self.set_to_parent()

    def visit_option(self, node):
        el = self.append_child('text:p', attrib={
            'text:style-name': 'Table_20_Contents'})
        el.text = node.astext()

    def depart_option(self, node):
        pass

    def visit_option_string(self, node):
        pass

    def depart_option_string(self, node):
        pass

    def visit_option_argument(self, node):
        pass

    def depart_option_argument(self, node):
        pass

    def visit_description(self, node):
        el = self.append_child('table:table-cell', attrib={
            'table:style-name': 'Table%d.B2' % self.table_count,
            'office:value-type': 'string',
        })
        el1 = SubElement(el, 'text:p', attrib={
            'text:style-name': 'Table_20_Contents'})
        el1.text = node.astext()
        raise nodes.SkipChildren()

    def depart_description(self, node):
        pass

    def visit_paragraph(self, node):
        self.in_paragraph = True
        if self.in_header:
            el = self.append_p('header')
        elif self.in_footer:
            el = self.append_p('footer')
        else:
            style_name = self.paragraph_style_stack[-1]
            el = self.append_child('text:p',
                attrib={'text:style-name': style_name})
            self.append_pending_ids(el)
        self.set_current_element(el)

    def depart_paragraph(self, node):
        self.in_paragraph = False
        self.set_to_parent()
        if self.in_header:
            self.header_content.append(
                self.current_element.getchildren()[-1])
            self.current_element.remove(
                self.current_element.getchildren()[-1])
        elif self.in_footer:
            self.footer_content.append(
                self.current_element.getchildren()[-1])
            self.current_element.remove(
                self.current_element.getchildren()[-1])

    def visit_problematic(self, node):
        pass

    def depart_problematic(self, node):
        pass

    def visit_raw(self, node):
        if 'format' in node.attributes:
            formats = node.attributes['format']
            formatlist = formats.split()
            if 'odt' in formatlist:
                rawstr = node.astext()
                attrstr = ' '.join(['%s="%s"' % (k, v, )
                    for k,v in CONTENT_NAMESPACE_ATTRIB.items()])
                contentstr = '<stuff %s>%s</stuff>' % (attrstr, rawstr, )
                if WhichElementTree != "lxml":
                    contentstr = contentstr.encode("utf-8")
                content = etree.fromstring(contentstr)
                elements = content.getchildren()
                if len(elements) > 0:
                    el1 = elements[0]
                    if self.in_header:
                        pass
                    elif self.in_footer:
                        pass
                    else:
                        self.current_element.append(el1)
        raise nodes.SkipChildren()

    def depart_raw(self, node):
        if self.in_header:
            pass
        elif self.in_footer:
            pass
        else:
            pass

    def visit_reference(self, node):
        text = node.astext()
        if self.settings.create_links:
            if node.has_key('refuri'):
                    href = node['refuri']
                    if ( self.settings.cloak_email_addresses
                         and href.startswith('mailto:')):
                        href = self.cloak_mailto(href)
                    el = self.append_child('text:a', attrib={
                        'xlink:href': '%s' % href,
                        'xlink:type': 'simple',
                        })
                    self.set_current_element(el)
            elif node.has_key('refid'):
                if self.settings.create_links:
                    href = node['refid']
                    el = self.append_child('text:reference-ref', attrib={
                        'text:ref-name': '%s' % href,
                        'text:reference-format': 'text',
                        })
            else:
                self.document.reporter.warning(
                    'References must have "refuri" or "refid" attribute.')
        if (self.in_table_of_contents and
            len(node.children) >= 1 and
            isinstance(node.children[0], docutils.nodes.generated)):
            node.remove(node.children[0])

    def depart_reference(self, node):
        if self.settings.create_links:
            if node.has_key('refuri'):
                self.set_to_parent()

    def visit_rubric(self, node):
        style_name = self.rststyle('rubric')
        classes = node.get('classes')
        if classes:
            class1 = classes[0]
            if class1:
                style_name = class1
        el = SubElement(self.current_element, 'text:h', attrib = {
            #'text:outline-level': '%d' % section_level,
            #'text:style-name': 'Heading_20_%d' % section_level,
            'text:style-name': style_name,
            })
        text = node.astext()
        el.text = self.encode(text)

    def depart_rubric(self, node):
        pass

    def visit_section(self, node, move_ids=1):
        self.section_level += 1
        self.section_count += 1
        if self.settings.create_sections:
            el = self.append_child('text:section', attrib={
                'text:name': 'Section%d' % self.section_count,
                'text:style-name': 'Sect%d' % self.section_level,
                })
            self.set_current_element(el)

    def depart_section(self, node):
        self.section_level -= 1
        if self.settings.create_sections:
            self.set_to_parent()

    def visit_strong(self, node):
        el = SubElement(self.current_element, 'text:span',
            attrib={'text:style-name': self.rststyle('strong')})
        self.set_current_element(el)

    def depart_strong(self, node):
        self.set_to_parent()

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

    def depart_substitution_definition(self, node):
        pass

    def visit_system_message(self, node):
        pass

    def depart_system_message(self, node):
        pass

    def get_table_style(self, node):
        table_style = None
        table_name = None
        use_predefined_table_style = False
        str_classes = node.get('classes')
        if str_classes is not None:
            for str_class in str_classes:
                if str_class.startswith(TABLESTYLEPREFIX):
                    table_name = str_class
                    use_predefined_table_style = True
                    break
        if table_name is not None:
            table_style = self.table_styles.get(table_name)
            if table_style is None:
                # If we can't find the table style, issue warning
                #   and use the default table style.
                self.document.reporter.warning(
                    'Can\'t find table style "%s".  Using default.' % (
                    table_name, ))
                table_name = TABLENAMEDEFAULT
                table_style = self.table_styles.get(table_name)
                if table_style is None:
                    # If we can't find the default table style, issue a warning
                    #   and use a built-in default style.
                    self.document.reporter.warning(
                        'Can\'t find default table style "%s".  Using built-in default.' % (
                        table_name, ))
                    table_style = BUILTIN_DEFAULT_TABLE_STYLE
        else:
            table_name = TABLENAMEDEFAULT
            table_style = self.table_styles.get(table_name)
            if table_style is None:
                # If we can't find the default table style, issue a warning
                #   and use a built-in default style.
                self.document.reporter.warning(
                    'Can\'t find default table style "%s".  Using built-in default.' % (
                    table_name, ))
                table_style = BUILTIN_DEFAULT_TABLE_STYLE
        return table_style

    def visit_table(self, node):
        self.table_count += 1
        table_style = self.get_table_style(node)
        table_name = '%s%%d' % TABLESTYLEPREFIX
        el1 = SubElement(self.automatic_styles, 'style:style', attrib={
            'style:name': self.rststyle(
                '%s' % table_name, ( self.table_count, )),
            'style:family': 'table',
            }, nsdict=SNSD)
        if table_style.backgroundcolor is None:
            el1_1 = SubElement(el1, 'style:table-properties', attrib={
                #'style:width': '17.59cm',
                #'table:align': 'margins',
                'table:align': 'left',
                'fo:margin-top': '0in',
                'fo:margin-bottom': '0.10in',
                }, nsdict=SNSD)
        else:
            el1_1 = SubElement(el1, 'style:table-properties', attrib={
                #'style:width': '17.59cm',
                'table:align': 'margins',
                'fo:margin-top': '0in',
                'fo:margin-bottom': '0.10in',
                'fo:background-color': table_style.backgroundcolor,
                }, nsdict=SNSD)
        # We use a single cell style for all cells in this table.
        # That's probably not correct, but seems to work.
        el2 = SubElement(self.automatic_styles, 'style:style', attrib={
            'style:name': self.rststyle(
                '%s.%%c%%d' % table_name, ( self.table_count, 'A', 1, )),
            'style:family': 'table-cell',
            }, nsdict=SNSD)
        thickness = self.settings.table_border_thickness
        if thickness is None:
            line_style1 = table_style.border
        else:
            line_style1 = '0.%03dcm solid #000000' % (thickness, )
        el2_1 = SubElement(el2, 'style:table-cell-properties', attrib={
            'fo:padding': '0.049cm',
            'fo:border-left': line_style1,
            'fo:border-right': line_style1,
            'fo:border-top': line_style1,
            'fo:border-bottom': line_style1,
            }, nsdict=SNSD)
        title = None
        for child in node.children:
            if child.tagname == 'title':
                title = child.astext()
                break
        if title is not None:
            el3 = self.append_p('table-title', title)
        else:
            pass
        el4 = SubElement(self.current_element, 'table:table', attrib={
            'table:name': self.rststyle(
                '%s' % table_name, ( self.table_count, )),
            'table:style-name': self.rststyle(
                '%s' % table_name, ( self.table_count, )),
            })
        self.set_current_element(el4)
        self.current_table_style = el1
        self.table_width = 0.0

    def depart_table(self, node):
        attribkey = add_ns('style:width', nsdict=SNSD)
        attribval = '%.4fin' % (self.table_width, )
        el1 = self.current_table_style
        el2 = el1[0]
        el2.attrib[attribkey] = attribval
        self.set_to_parent()

    def visit_tgroup(self, node):
        self.column_count = ord('A') - 1

    def depart_tgroup(self, node):
        pass

    def visit_colspec(self, node):
        self.column_count += 1
        colspec_name = self.rststyle(
            '%s%%d.%%s' % TABLESTYLEPREFIX,
            (self.table_count, chr(self.column_count), )
            )
        colwidth = node['colwidth'] / 12.0
        el1 = SubElement(self.automatic_styles, 'style:style', attrib={
            'style:name': colspec_name,
            'style:family': 'table-column',
            }, nsdict=SNSD)
        el1_1 = SubElement(el1, 'style:table-column-properties', attrib={
            'style:column-width': '%.4fin' % colwidth 
            },
            nsdict=SNSD)
        el2 = self.append_child('table:table-column', attrib={
            'table:style-name': colspec_name,
            })
        self.table_width += colwidth

    def depart_colspec(self, node):
        pass

    def visit_thead(self, node):
        el = self.append_child('table:table-header-rows')
        self.set_current_element(el)
        self.in_thead = True
        self.paragraph_style_stack.append('Table_20_Heading')

    def depart_thead(self, node):
        self.set_to_parent()
        self.in_thead = False
        self.paragraph_style_stack.pop()

    def visit_row(self, node):
        self.column_count = ord('A') - 1
        el = self.append_child('table:table-row')
        self.set_current_element(el)

    def depart_row(self, node):
        self.set_to_parent()

    def visit_entry(self, node):
        self.column_count += 1
        cellspec_name = self.rststyle(
            '%s%%d.%%c%%d' % TABLESTYLEPREFIX, 
            (self.table_count, 'A', 1, )
            )
        attrib={
            'table:style-name': cellspec_name,
            'office:value-type': 'string',
            }
        morecols = node.get('morecols', 0)
        if morecols > 0:
            attrib['table:number-columns-spanned'] = '%d' % (morecols + 1,)
            self.column_count += morecols
        morerows = node.get('morerows', 0)
        if morerows > 0:
            attrib['table:number-rows-spanned'] = '%d' % (morerows + 1,)
        el1 = self.append_child('table:table-cell', attrib=attrib)
        self.set_current_element(el1)

    def depart_entry(self, node):
        self.set_to_parent()

    def visit_tbody(self, node):
        pass

    def depart_tbody(self, node):
        pass

    def visit_target(self, node):
        #
        # I don't know how to implement targets in ODF.
        # How do we create a target in oowriter?  A cross-reference?
        if not (node.has_key('refuri') or node.has_key('refid')
                or node.has_key('refname')):
            pass
        else:
            pass

    def depart_target(self, node):
        pass

    def visit_title(self, node, move_ids=1, title_type='title'):
        if isinstance(node.parent, docutils.nodes.section):
            section_level = self.section_level
            if section_level > 7:
                self.document.reporter.warning(
                    'Heading/section levels greater than 7 not supported.')
                self.document.reporter.warning(
                    '    Reducing to heading level 7 for heading: "%s"' % (
                        node.astext(), ))
                section_level = 7
            el1 = self.append_child('text:h', attrib = {
                'text:outline-level': '%d' % section_level,
                #'text:style-name': 'Heading_20_%d' % section_level,
                'text:style-name': self.rststyle(
                    'heading%d', (section_level, )),
                })
            self.append_pending_ids(el1)
            self.set_current_element(el1)
        elif isinstance(node.parent, docutils.nodes.document):
            #    text = self.settings.title
            #else:
            #    text = node.astext()
            el1 = SubElement(self.current_element, 'text:p', attrib = {
                'text:style-name': self.rststyle(title_type),
                })
            self.append_pending_ids(el1)
            text = node.astext()
            self.title = text
            self.found_doc_title = True
            self.set_current_element(el1)

    def depart_title(self, node):
        if (isinstance(node.parent, docutils.nodes.section) or
            isinstance(node.parent, docutils.nodes.document)):
            self.set_to_parent()

    def visit_subtitle(self, node, move_ids=1):
        self.visit_title(node, move_ids, title_type='subtitle')

    def depart_subtitle(self, node):
        self.depart_title(node)

    def visit_title_reference(self, node):
        el = self.append_child('text:span', attrib={
            'text:style-name': self.rststyle('quotation')})
        el.text = self.encode(node.astext())
        raise nodes.SkipChildren()

    def depart_title_reference(self, node):
        pass

    def generate_table_of_content_entry_template(self, el1):
        for idx in range(1, 11):
            el2 = SubElement(el1, 
                'text:table-of-content-entry-template', 
                attrib={
                    'text:outline-level': "%d" % (idx, ),
                    'text:style-name': self.rststyle('contents-%d' % (idx, )),
                })
            el3 = SubElement(el2, 'text:index-entry-chapter')
            el3 = SubElement(el2, 'text:index-entry-text')
            el3 = SubElement(el2, 'text:index-entry-tab-stop', attrib={
                'style:leader-char': ".",
                'style:type': "right",
                })
            el3 = SubElement(el2, 'text:index-entry-page-number')

    def find_title_label(self, node, class_type, label_key):
        label = ''
        title_node = None
        for child in node.children:
            if isinstance(child, class_type):
                title_node = child
                break
        if title_node is not None:
            label = title_node.astext()
        else:
            label = self.language.labels[label_key]
        return label

    def visit_topic(self, node):
        if 'classes' in node.attributes:
            if 'contents' in node.attributes['classes']:
                label = self.find_title_label(node, docutils.nodes.title,
                    'contents')
                if self.settings.generate_oowriter_toc:
                    el1 = self.append_child('text:table-of-content', attrib={
                        'text:name': 'Table of Contents1',
                        'text:protected': 'true',
                        'text:style-name': 'Sect1',
                        })
                    el2 = SubElement(el1,
                        'text:table-of-content-source',
                        attrib={
                            'text:outline-level': '10',
                        })
                    el3 =SubElement(el2, 'text:index-title-template', attrib={
                        'text:style-name': 'Contents_20_Heading',
                        })
                    el3.text = label
                    self.generate_table_of_content_entry_template(el2)
                    el4 = SubElement(el1, 'text:index-body')
                    el5 = SubElement(el4, 'text:index-title')
                    el6 = SubElement(el5, 'text:p', attrib={
                        'text:style-name': self.rststyle('contents-heading'),
                        })
                    el6.text = label
                    self.save_current_element = self.current_element
                    self.table_of_content_index_body = el4
                    self.set_current_element(el4)
                else:
                    el = self.append_p('horizontalline')
                    el = self.append_p('centeredtextbody')
                    el1 = SubElement(el, 'text:span',
                        attrib={'text:style-name': self.rststyle('strong')})
                    el1.text = label
                self.in_table_of_contents = True
            elif 'abstract' in node.attributes['classes']:
                el = self.append_p('horizontalline')
                el = self.append_p('centeredtextbody')
                el1 = SubElement(el, 'text:span',
                    attrib={'text:style-name': self.rststyle('strong')})
                label = self.find_title_label(node, docutils.nodes.title,
                    'abstract')
                el1.text = label
            elif 'dedication' in node.attributes['classes']:
                el = self.append_p('horizontalline')
                el = self.append_p('centeredtextbody')
                el1 = SubElement(el, 'text:span',
                    attrib={'text:style-name': self.rststyle('strong')})
                label = self.find_title_label(node, docutils.nodes.title,
                    'dedication')
                el1.text = label

    def depart_topic(self, node):
        if 'classes' in node.attributes:
            if 'contents' in node.attributes['classes']:
                if self.settings.generate_oowriter_toc:
                    self.update_toc_page_numbers(
                        self.table_of_content_index_body)
                    self.set_current_element(self.save_current_element)
                else:
                    el = self.append_p('horizontalline')
                self.in_table_of_contents = False

    def update_toc_page_numbers(self, el):
        collection = []
        self.update_toc_collect(el, 0, collection)
        self.update_toc_add_numbers(collection)

    def update_toc_collect(self, el, level, collection):
        collection.append((level, el))
        level += 1
        for child_el in el.getchildren():
            if child_el.tag != 'text:index-body':
                self.update_toc_collect(child_el, level, collection)

    def update_toc_add_numbers(self, collection):
        for level, el1 in collection:
            if (el1.tag == 'text:p' and
                el1.text != 'Table of Contents'):
                el2 = SubElement(el1, 'text:tab')
                el2.tail = '9999'


    def visit_transition(self, node):
        el = self.append_p('horizontalline')

    def depart_transition(self, node):
        pass

    #
    # Admonitions
    #
    def visit_warning(self, node):
        self.generate_admonition(node, 'warning')

    def depart_warning(self, node):
        self.paragraph_style_stack.pop()

    def visit_attention(self, node):
        self.generate_admonition(node, 'attention')

    depart_attention = depart_warning

    def visit_caution(self, node):
        self.generate_admonition(node, 'caution')

    depart_caution = depart_warning

    def visit_danger(self, node):
        self.generate_admonition(node, 'danger')

    depart_danger = depart_warning

    def visit_error(self, node):
        self.generate_admonition(node, 'error')

    depart_error = depart_warning

    def visit_hint(self, node):
        self.generate_admonition(node, 'hint')

    depart_hint = depart_warning

    def visit_important(self, node):
        self.generate_admonition(node, 'important')

    depart_important = depart_warning

    def visit_note(self, node):
        self.generate_admonition(node, 'note')

    depart_note = depart_warning

    def visit_tip(self, node):
        self.generate_admonition(node, 'tip')

    depart_tip = depart_warning

    def visit_admonition(self, node):
        title = None
        for child in node.children:
            if child.tagname == 'title':
                title = child.astext()
        if title is None:
            classes1 = node.get('classes')
            if classes1:
                title = classes1[0]
        self.generate_admonition(node, 'generic', title)

    depart_admonition = depart_warning

    def generate_admonition(self, node, label, title=None):
        el1 = SubElement(self.current_element, 'text:p', attrib = {
            'text:style-name': self.rststyle('admon-%s-hdr', ( label, )),
            })
        if title:
            el1.text = title
        else:
            el1.text = '%s!' % (label.capitalize(), )
        s1 = self.rststyle('admon-%s-body', ( label, ))
        self.paragraph_style_stack.append(s1)

    #
    # Roles (e.g. subscript, superscript, strong, ...
    #
    def visit_subscript(self, node):
        el = self.append_child('text:span', attrib={
            'text:style-name': 'rststyle-subscript',
            })
        self.set_current_element(el)

    def depart_subscript(self, node):
        self.set_to_parent()

    def visit_superscript(self, node):
        el = self.append_child('text:span', attrib={
            'text:style-name': 'rststyle-superscript',
            })
        self.set_current_element(el)

    def depart_superscript(self, node):
        self.set_to_parent()


# Use an own reader to modify transformations done.
class Reader(standalone.Reader):

    def get_transforms(self):
        default = standalone.Reader.get_transforms(self)
        if self.settings.create_links:
            return default
        return [ i
                 for i in default
                 if i is not references.DanglingReferences ]