emacs-orgmode@gnu.org archives
 help / color / mirror / code / Atom feed
blob a5b2d96bad4c40fb9ea0c9b83836ad3b2a5ccab1 66706 bytes (raw)
name: contrib/lisp/org-odt.el 	 # note: path name is non-authoritative(*)

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
 
;;; org-odt.el --- OpenDocumentText export for Org-mode

;; Copyright (C) 2010-2011 Jambunathan <kjambunathan at gmail dot com>

;; Author: Jambunathan K <kjambunathan at gmail dot com>
;; Keywords: outlines, hypermedia, calendar, wp
;; Homepage: http://orgmode.org
;; Version: 0.8

;; This file is not (yet) part of GNU Emacs.
;; However, it is distributed under the same license.

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

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

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

;;; Code:
(eval-when-compile (require 'cl))
(require 'org-lparse)

(defun org-odt-end-export ()
  ;; remove empty paragraphs
  (goto-char (point-min))
  (while (re-search-forward
	  "<text:p\\( text:style-name=\"Text_20_body\"\\)?>[ \r\n\t]*</text:p>"
	  nil t)
    (replace-match ""))
  (goto-char (point-min))

  ;; Convert whitespace place holders
  (goto-char (point-min))
  (let (beg end n)
    (while (setq beg (next-single-property-change (point) 'org-whitespace))
      (setq n (get-text-property beg 'org-whitespace)
	    end (next-single-property-change beg 'org-whitespace))
      (goto-char beg)
      (delete-region beg end)
      (insert (format "<span style=\"visibility:hidden;\">%s</span>"
		      (make-string n ?x)))))

  ;; Remove empty lines at the beginning of the file.
  (goto-char (point-min))
  (when (looking-at "\\s-+\n") (replace-match ""))

  ;; Remove display properties
  (remove-text-properties (point-min) (point-max) '(display t)))

(defvar org-odt-suppress-xref nil)
(defconst org-export-odt-special-string-regexps
  '(("\\\\-" . "&#x00ad;\\1")		; shy
    ("---\\([^-]\\)" . "&#x2014;\\1")	; mdash
    ("--\\([^-]\\)" . "&#x2013;\\1")	; ndash
    ("\\.\\.\\." . "&#x2026;"))		; hellip
  "Regular expressions for special string conversion.")

(defconst org-odt-lib-dir (file-name-directory load-file-name))
(defconst org-odt-data-dir
  (let ((dir1 (expand-file-name "../odt" org-odt-lib-dir))	   ; git
	(dir2 (expand-file-name "./contrib/odt" org-odt-lib-dir))) ; elpa
    (cond
     ((file-directory-p dir1) dir1)
     ((file-directory-p dir2) dir2)
     (t (error "Cannot find factory styles file. Check package dir layout"))))
  "Directory that holds auxiliary files used by the ODT exporter.

The 'styles' subdir contains the following xml files -
 'OrgOdtStyles.xml' and 'OrgOdtAutomaticStyles.xml' - which are
 used as factory settings of `org-export-odt-styles-file' and
 `org-export-odt-automatic-styles-file'.

The 'etc/schema' subdir contains rnc files for validating of
OpenDocument xml files.")

(defvar org-odt-file-extensions
  '(("odt" . "OpenDocument Text")
    ("ott" . "OpenDocument Text Template")
    ("odm" . "OpenDocument Master Document")
    ("ods" . "OpenDocument Spreadsheet")
    ("ots" . "OpenDocument Spreadsheet Template")
    ("odg" . "OpenDocument Drawing (Graphics)")
    ("otg" . "OpenDocument Drawing Template")
    ("odp" . "OpenDocument Presentation")
    ("otp" . "OpenDocument Presentation Template")
    ("odi" . "OpenDocument Image")
    ("odf" . "OpenDocument Formula")
    ("odc" . "OpenDocument Chart")
    ("doc" . "Microsoft Text")
    ("docx" . "Microsoft Text")
    ("xls" . "Microsoft Spreadsheet")
    ("xlsx" . "Microsoft Spreadsheet")
    ("ppt" . "Microsoft Presentation")
    ("pptx" . "Microsoft Presentation")))

(defvar org-odt-ms-file-extensions
  '(("doc" . "Microsoft Text")
    ("docx" . "Microsoft Text")
    ("xls" . "Microsoft Spreadsheet")
    ("xlsx" . "Microsoft Spreadsheet")
    ("ppt" . "Microsoft Presentation")
    ("pptx" . "Microsoft Presentation")))

;; RelaxNG validation of OpenDocument xml files
(eval-after-load 'rng-nxml
  '(setq rng-nxml-auto-validate-flag t))

(eval-after-load 'rng-loc
  '(add-to-list 'rng-schema-locating-files
		(expand-file-name "etc/schema/schemas.xml" org-odt-data-dir)))

(mapc
 (lambda (desc)
   ;; Let Org open all OpenDocument files using system-registered app
   (add-to-list 'org-file-apps
		(cons (concat  "\\." (car desc) "\\'") 'system))
   ;; Let Emacs open all OpenDocument files in archive mode
   (add-to-list 'auto-mode-alist
		(cons (concat  "\\." (car desc) "\\'") 'archive-mode)))
 org-odt-file-extensions)

(mapc
 (lambda (desc)
   ;; Let Org open all Microsoft files using system-registered app
   (add-to-list 'org-file-apps
		(cons (concat  "\\." (car desc) "\\'") 'system)))
 org-odt-ms-file-extensions)

;; register the odt exporter with the pre-processor
(add-to-list 'org-export-backends 'odt)

;; register the odt exporter with org-lparse library
(org-lparse-register-backend 'odt)

(defun org-odt-unload-function ()
  (org-lparse-unregister-backend 'odt)
  (remove-hook 'org-export-preprocess-after-blockquote-hook
	       'org-export-odt-preprocess-latex-fragments)
  nil)

(defcustom org-export-odt-automatic-styles-file nil
  "Automatic styles for use with ODT exporter.
If unspecified, the file under `org-odt-data-dir' is used."
  :type 'file
  :group 'org-export-odt)

(defcustom org-export-odt-styles-file nil
  "Default styles file for use with ODT export.
Valid values are one of:
1. nil
2. path to a styles.xml file
3. path to a *.odt or a *.ott file
4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
...))

In case of option 1, an in-built styles.xml is used. See
`org-odt-data-dir' for more information.

In case of option 3, the specified file is unzipped and the
styles.xml embedded therein is used.

In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
generated odt file.  Use relative path for specifying the
FILE-MEMBERS.  styles.xml must be specified as one of the
FILE-MEMBERS.

Use options 1, 2 or 3 only if styles.xml alone suffices for
achieving the desired formatting.  Use option 4, if the styles.xml
references additional files like header and footer images for
achieving the desired formattting."
  :group 'org-export-odt
  :type
  '(choice
    (const :tag "Factory settings" nil)
    (file :must-match t :tag "styles.xml")
    (file :must-match t :tag "ODT or OTT file")
    (list :tag "ODT or OTT file + Members"
	  (file :must-match t :tag "ODF Text or Text Template file")
	  (cons :tag "Members"
		(file :tag "	Member" "styles.xml")
		(repeat (file :tag "Member"))))))

(defconst org-export-odt-tmpdir-prefix "odt-")
(defconst org-export-odt-bookmark-prefix "OrgXref.")
(defcustom org-export-odt-use-bookmarks-for-internal-links t
  "Export Internal links as bookmarks?."
  :type 'boolean
  :group 'org-export-odt)

(defcustom org-export-odt-embed-images t
  "Should the images be copied in to the odt file or just linked?"
  :type 'boolean
  :group 'org-export-odt)

(defcustom org-odt-export-inline-images 'maybe
  "Non-nil means inline images into exported HTML pages.
This is done using an <img> tag.  When nil, an anchor with href is used to
link to the image.  If this option is `maybe', then images in links with
an empty description will be inlined, while images with a description will
be linked only."
  :group 'org-odt-export
  :type '(choice (const :tag "Never" nil)
		 (const :tag "Always" t)
		 (const :tag "When there is no description" maybe)))

(defcustom org-odt-export-inline-image-extensions
  '("png" "jpeg" "jpg" "gif")
  "Extensions of image files that can be inlined into HTML."
  :type '(repeat (string :tag "Extension"))
  :group 'org-odt-export)

(defcustom org-export-odt-pixels-per-inch display-pixels-per-inch
  ;; FIXME add docstring
  ""
  :type 'float
  :group 'org-export-odt)

(defvar org-export-odt-default-org-styles-alist
  '((paragraph . ((default . "Text_20_body")
		  (fixedwidth . "OrgFixedWidthBlock")
		  (verse . "OrgVerse")
		  (quote . "Quotations")
		  (blockquote . "Quotations")
		  (center . "OrgCenter")
		  (left . "OrgLeft")
		  (right . "OrgRight")
		  (title . "Heading_20_1.title")
		  (footnote . "Footnote")
		  (src . "OrgSrcBlock")
		  (illustration . "Illustration")
		  (table . "Table")
		  (definition-term . "Text_20_body_20_bold")
		  (horizontal-line . "Horizontal_20_Line")))
    (character . ((bold . "Bold")
		  (emphasis . "Emphasis")
		  (code . "OrgCode")
		  (verbatim . "OrgCode")
		  (strike . "Strikethrough")
		  (underline . "Underline")
		  (subscript . "OrgSubscript")
		  (superscript . "OrgSuperscript")))
    (list . ((ordered . "OrgNumberedList")
	     (unordered . "OrgBulletedList")
	     (description . "OrgDescriptionList"))))
  "Default styles for various entities.")

(defvar org-export-odt-org-styles-alist org-export-odt-default-org-styles-alist)
(defun org-odt-get-style-name-for-entity (category &optional entity)
  (let ((entity (or entity 'default)))
    (or
     (cdr (assoc entity (cdr (assoc category
				    org-export-odt-org-styles-alist))))
     (cdr (assoc entity (cdr (assoc category
				    org-export-odt-default-org-styles-alist))))
     (error "Cannot determine style name for entity %s of type %s"
	    entity category))))

(defcustom org-export-odt-preferred-output-format nil
  "Automatically post-process to this format after exporting to \"odt\".
Interactive commands `org-export-as-odt' and
`org-export-as-odt-and-open' export first to \"odt\" format and
then use an external converter to convert the resulting document
to this format.

The converter used is that specified with CONVERT-METHOD option
in `org-odt-get'. If the above option is unspecified then
`org-lparse-convert-process' is used.

The format specified here should be listed in OTHER-BACKENDS
option of `org-odt-get' or `org-lparse-convert-capabilities' as
appropriate."
  :group 'org-odt
  :type '(choice :convert-widget
		 (lambda (w)
		   (apply 'widget-convert (widget-type w)
			  (eval (car (widget-get w :args)))))
		 `((const :tag "None" nil)
		   ,@(mapcar (lambda (c)
			       `(const :tag ,(car c) ,(car c)))
			     (org-lparse-get-other-backends "odt")))))

;;;###autoload
(defun org-export-as-odt-and-open (arg)
  "Export the outline as ODT and immediately open it with a browser.
If there is an active region, export only the region.
The prefix ARG specifies how many levels of the outline should become
headlines.  The default is 3.  Lower levels will become bulleted lists."
  (interactive "P")
  (org-lparse-and-open
   (or org-export-odt-preferred-output-format "odt") "odt" arg))

;;;###autoload
(defun org-export-as-odt-batch ()
  "Call the function `org-lparse-batch'.
This function can be used in batch processing as:
emacs   --batch
        --load=$HOME/lib/emacs/org.el
        --eval \"(setq org-export-headline-levels 2)\"
        --visit=MyFile --funcall org-export-as-odt-batch"
  (org-lparse-batch "odt"))

;;;###autoload
(defun org-export-as-odt-to-buffer (arg)
  "Call `org-lparse-odt` with output to a temporary buffer.
No file is created.  The prefix ARG is passed through to `org-lparse-to-buffer'."
  (interactive "P")
  (org-lparse-to-buffer "odt" arg))

;;;###autoload
(defun org-replace-region-by-odt (beg end)
  "Assume the current region has org-mode syntax, and convert it to ODT.
This can be used in any buffer.  For example, you could write an
itemized list in org-mode syntax in an ODT buffer and then use this
command to convert it."
  (interactive "r")
  (org-replace-region-by "odt" beg end))

;;;###autoload
(defun org-export-region-as-odt (beg end &optional body-only buffer)
  "Convert region from BEG to END in org-mode buffer to ODT.
If prefix arg BODY-ONLY is set, omit file header, footer, and table of
contents, and only produce the region of converted text, useful for
cut-and-paste operations.
If BUFFER is a buffer or a string, use/create that buffer as a target
of the converted ODT.  If BUFFER is the symbol `string', return the
produced ODT as a string and leave not buffer behind.  For example,
a Lisp program could call this function in the following way:

  (setq odt (org-export-region-as-odt beg end t 'string))

When called interactively, the output buffer is selected, and shown
in a window.  A non-interactive call will only return the buffer."
  (interactive "r\nP")
  (org-lparse-region "odt" beg end body-only buffer))

;;; org-export-as-odt
;;;###autoload
(defun org-export-as-odt (arg &optional hidden ext-plist
			      to-buffer body-only pub-dir)
  "Export the outline as a OpenDocumentText file.
If there is an active region, export only the region.  The prefix
ARG specifies how many levels of the outline should become
headlines.  The default is 3.  Lower levels will become bulleted
lists.  HIDDEN is obsolete and does nothing.
EXT-PLIST is a property list with external parameters overriding
org-mode's default settings, but still inferior to file-local
settings.  When TO-BUFFER is non-nil, create a buffer with that
name and export to that buffer.  If TO-BUFFER is the symbol
`string', don't leave any buffer behind but just return the
resulting XML as a string.  When BODY-ONLY is set, don't produce
the file header and footer, simply return the content of
<body>...</body>, without even the body tags themselves.  When
PUB-DIR is set, use this as the publishing directory."
  (interactive "P")
  (org-lparse (or org-export-odt-preferred-output-format "odt")
	      "odt" arg hidden ext-plist to-buffer body-only pub-dir))

(defvar org-odt-entity-control-callbacks-alist
  `((EXPORT
     . (org-odt-begin-export org-odt-end-export))
    (DOCUMENT-CONTENT
     . (org-odt-begin-document-content org-odt-end-document-content))
    (DOCUMENT-BODY
     . (org-odt-begin-document-body org-odt-end-document-body))
    (TOC
     . (org-odt-begin-toc org-odt-end-toc))
    (ENVIRONMENT
     . (org-odt-begin-environment org-odt-end-environment))
    (FOOTNOTE-DEFINITION
     . (org-odt-begin-footnote-definition org-odt-end-footnote-definition))
    (TABLE
     . (org-odt-begin-table org-odt-end-table))
    (TABLE-ROWGROUP
     . (org-odt-begin-table-rowgroup org-odt-end-table-rowgroup))
    (LIST
     . (org-odt-begin-list org-odt-end-list))
    (LIST-ITEM
     . (org-odt-begin-list-item org-odt-end-list-item))
    (OUTLINE
     . (org-odt-begin-outline org-odt-end-outline))
    (OUTLINE-TEXT
     . (org-odt-begin-outline-text org-odt-end-outline-text))
    (PARAGRAPH
     . (org-odt-begin-paragraph org-odt-end-paragraph)))
  "")

(defvar org-odt-entity-format-callbacks-alist
  `((EXTRA-TARGETS . org-lparse-format-extra-targets)
    (ORG-TAGS . org-lparse-format-org-tags)
    (SECTION-NUMBER . org-lparse-format-section-number)
    (HEADLINE . org-odt-format-headline)
    (TOC-ENTRY . org-odt-format-toc-entry)
    (TOC-ITEM . org-odt-format-toc-item)
    (TAGS . org-odt-format-tags)
    (SPACES . org-odt-format-spaces)
    (TABS . org-odt-format-tabs)
    (LINE-BREAK . org-odt-format-line-break)
    (FONTIFY . org-odt-format-fontify)
    (TODO . org-lparse-format-todo)
    (LINK . org-odt-format-link)
    (INLINE-IMAGE . org-odt-format-inline-image)
    (ORG-LINK . org-odt-format-org-link)
    (HEADING . org-odt-format-heading)
    (ANCHOR . org-odt-format-anchor)
    (TABLE . org-lparse-format-table)
    (TABLE-ROW . org-odt-format-table-row)
    (TABLE-CELL . org-odt-format-table-cell)
    (FOOTNOTES-SECTION . ignore)
    (FOOTNOTE-REFERENCE . org-odt-format-footnote-reference)
    (HORIZONTAL-LINE . org-odt-format-horizontal-line)
    (COMMENT . org-odt-format-comment)
    (LINE . org-odt-format-line)
    (ORG-ENTITY . org-odt-format-org-entity))
  "")

;;;_. callbacks
;;;_. control callbacks
;;;_ , document body
(defun org-odt-begin-office-body ()
  (insert "
  <office:body>
    <office:text>
      <text:sequence-decls>
	<text:sequence-decl text:display-outline-level=\"0\" text:name=\"Illustration\"/>
	<text:sequence-decl text:display-outline-level=\"0\" text:name=\"Table\"/>
	<text:sequence-decl text:display-outline-level=\"0\" text:name=\"Text\"/>
	<text:sequence-decl text:display-outline-level=\"0\" text:name=\"Drawing\"/>
	<text:sequence-decl text:display-outline-level=\"0\" text:name=\"Equation\"/>
      </text:sequence-decls>"))

;; Following variable is let bound when `org-do-lparse' is in
;; progress. See org-html.el.
(defvar org-lparse-toc)
(defun org-odt-begin-document-body (opt-plist)
  (org-odt-begin-office-body)
  (let ((title (plist-get opt-plist :title)))
    (when title
      (insert
       (org-odt-format-stylized-paragraph 'title title))))

  ;; insert toc
  (when org-lparse-toc
    (insert "\n" org-lparse-toc "\n")))

(defvar org-lparse-body-only)		; let bound during org-do-lparse
(defvar org-lparse-to-buffer)		; let bound during org-do-lparse
(defun org-odt-end-document-body (opt-plist)
  (unless org-lparse-body-only
    (org-lparse-insert-tag "</office:text>")
    (org-lparse-insert-tag "</office:body>")))

(defconst org-odt-document-content-header
  "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<office:document-content
    xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
    xmlns:style=\"urn:oasis:names:tc:opendocument:xmlns:style:1.0\"
    xmlns:text=\"urn:oasis:names:tc:opendocument:xmlns:text:1.0\"
    xmlns:table=\"urn:oasis:names:tc:opendocument:xmlns:table: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:xlink=\"http://www.w3.org/1999/xlink\"
    xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
    xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
    xmlns:number=\"urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0\"
    xmlns:svg=\"urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0\"
    xmlns:chart=\"urn:oasis:names:tc:opendocument:xmlns:chart:1.0\"
    xmlns:dr3d=\"urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0\"
    xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
    xmlns:form=\"urn:oasis:names:tc:opendocument:xmlns:form:1.0\"
    xmlns:script=\"urn:oasis:names:tc:opendocument:xmlns:script:1.0\"
    xmlns:ooo=\"http://openoffice.org/2004/office\"
    xmlns:ooow=\"http://openoffice.org/2004/writer\"
    xmlns:oooc=\"http://openoffice.org/2004/calc\"
    xmlns:dom=\"http://www.w3.org/2001/xml-events\"
    xmlns:xforms=\"http://www.w3.org/2002/xforms\"
    xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"
    xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
    xmlns:rpt=\"http://openoffice.org/2005/report\"
    xmlns:of=\"urn:oasis:names:tc:opendocument:xmlns:of:1.2\"
    xmlns:xodt=\"http://www.w3.org/1999/xodt\"
    xmlns:field=\"urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0\"    office:version=\"1.2\">
")

(defun org-odt-begin-document-content (opt-plist)
  ;; document header
  (insert org-odt-document-content-header)

  ;; automatic styles
  (insert-file-contents
   (or org-export-odt-automatic-styles-file
       (expand-file-name "styles/OrgOdtAutomaticStyles.xml"
			 org-odt-data-dir)))
   (goto-char (point-max)))

(defun org-odt-end-document-content ()
  (org-lparse-insert-tag "</office:document-content>"))

(defun org-odt-begin-outline (level1 snumber title tags
				     target extra-targets class)
  (org-lparse-insert
   'HEADING (org-lparse-format
	     'HEADLINE title extra-targets tags snumber level1)
   level1 target))

(defun org-odt-end-outline ()
  (ignore))

(defun org-odt-begin-outline-text (level1 snumber class)
  (ignore))

(defun org-odt-end-outline-text ()
  (ignore))

(defun org-odt-begin-paragraph (&optional style)
  (org-lparse-insert-tag
   "<text:p%s>" (org-odt-get-extra-attrs-for-paragraph-style style)))

(defun org-odt-end-paragraph ()
  (org-lparse-insert-tag "</text:p>"))

(defun org-odt-get-extra-attrs-for-paragraph-style (style)
  (let (style-name)
    (setq style-name
	  (cond
	   ((stringp style) style)
	   ((symbolp style) (org-odt-get-style-name-for-entity
			     'paragraph style))))
    (unless style-name
      (error "Don't know how to handle paragraph style %s" style))
    (format " text:style-name=\"%s\"" style-name)))

(defun org-odt-format-stylized-paragraph (style text)
  (org-odt-format-tags
   '("<text:p%s>" . "</text:p>") text
   (org-odt-get-extra-attrs-for-paragraph-style style)))

(defun org-odt-begin-environment (style)
  (case style
    ((blockquote verse center quote)
     (org-lparse-begin-paragraph style)
     (list))
    ((fixedwidth native)
     (org-lparse-end-paragraph)
     (list))
    (t (error "Unknown environment %s" style))))

(defun org-odt-end-environment (style)
  (case style
    ((blockquote verse center quote)
     (org-lparse-end-paragraph)
     (list))
    ((fixedwidth native)
     (org-lparse-begin-paragraph)
     (list))
    (t (error "Unknown environment %s" style))))

(defvar org-lparse-list-level) ; dynamically bound in org-do-lparse
(defun org-odt-begin-list (ltype)
  (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
		  ltype))
  (let* ((style-name (org-odt-get-style-name-for-entity 'list ltype))
	 (extra (concat (when (= org-lparse-list-level 1)
			  " text:continue-numbering=\"false\"")
			(when style-name
			  (format " text:style-name=\"%s\""  style-name)))))
    (case ltype
      ((ordered unordered description)
       (org-lparse-end-paragraph)
       (org-lparse-insert-tag "<text:list%s>" extra))
      (t (error "Unknown list type: %s"  ltype)))))

(defun org-odt-end-list (ltype)
  (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
		  ltype))
  (if ltype
      (org-lparse-insert-tag "</text:list>")
    (error "Unknown list type: %s" ltype)))

(defun org-odt-begin-list-item (ltype &optional arg headline)
  (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
		  ltype))
  (case ltype
    (ordered
     (assert (not headline) t)
     (let* ((counter arg) (extra ""))
       (org-lparse-insert-tag "<text:list-item>")
       (org-lparse-begin-paragraph)))
    (unordered
     (let* ((id arg) (extra ""))
       (org-lparse-insert-tag "<text:list-item>")
       (org-lparse-begin-paragraph)
       (insert (if headline (org-odt-format-target headline id)
		 (org-odt-format-bookmark "" id)))))
    (description
     (assert (not headline) t)
     (let ((term (or arg "(no term)")))
       (insert
	(org-odt-format-tags
	 '("<text:list-item>" . "</text:list-item>")
	 (org-odt-format-stylized-paragraph 'definition-term term)))
       (org-lparse-begin 'LIST-ITEM 'unordered)
       (org-lparse-begin-list 'description)
       (org-lparse-begin 'LIST-ITEM 'unordered)))
    (t (error "Unknown list type"))))

(defun org-odt-end-list-item (ltype)
  (setq ltype (or (org-lparse-html-list-type-to-canonical-list-type ltype)
		  ltype))
  (case ltype
    ((ordered unordered)
     (org-lparse-insert-tag "</text:list-item>"))
    (description
     (org-lparse-end-list-item)
     (org-lparse-end-list 'description)
     (org-lparse-end-list-item))
    (t (error "Unknown list type"))))

;; Following variables are let bound when table emission is in
;; progress. See org-lparse.el.
(defvar org-lparse-table-begin-marker)
(defvar org-lparse-table-ncols)
(defvar org-lparse-table-rowgrp-open)
(defvar org-lparse-table-rownum)
(defvar org-lparse-table-cur-rowgrp-is-hdr)
(defvar org-lparse-table-is-styled)
(defvar org-lparse-table-rowgrp-info)
(defvar org-lparse-table-colalign-vector)
(defun org-odt-begin-table (caption label attributes)
  (when label
    (insert
     (org-odt-format-stylized-paragraph
      'table (org-odt-format-entity-caption label caption "Table"))))

  (org-lparse-insert-tag
   "<table:table table:name=\"%s\" table:style-name=\"%s\">"
   (or label "") "OrgTable")
  (setq org-lparse-table-begin-marker (point)))

(defun org-odt-end-table ()
  (goto-char org-lparse-table-begin-marker)
  (loop for level from 0 below org-lparse-table-ncols
	do (insert
	    (org-odt-format-tags
	     "<table:table-column table:style-name=\"OrgTableColumn\"/>"  "")))

  ;; fill style attributes for table cells
  (when org-lparse-table-is-styled
    (while (re-search-forward "@@\\(table-cell:p\\|table-cell:style-name\\)@@\\([0-9]+\\)@@\\([0-9]+\\)@@" nil t)
      (let ((spec (match-string 1))
	    (r (string-to-number (match-string 2)))
	    (c (string-to-number (match-string 3))))
	(cond
	 ((equal spec "table-cell:p")
	  (let ((style-name (org-odt-get-paragraph-style-for-table-cell r c)))
	    (replace-match style-name t t)))
	 ((equal spec "table-cell:style-name")
	  (let ((style-name (org-odt-get-style-name-for-table-cell r c)))
	    (replace-match style-name t t)))))))

  (goto-char (point-max))
  (org-lparse-insert-tag "</table:table>"))

(defun org-odt-begin-table-rowgroup (&optional is-header-row)
  (when org-lparse-table-rowgrp-open
    (org-lparse-end 'TABLE-ROWGROUP))
  (org-lparse-insert-tag (if is-header-row
			   "<table:table-header-rows>"
			 "<table:table-rows>"))
  (setq org-lparse-table-rowgrp-open t)
  (setq org-lparse-table-cur-rowgrp-is-hdr is-header-row))

(defun org-odt-end-table-rowgroup ()
  (when org-lparse-table-rowgrp-open
    (setq org-lparse-table-rowgrp-open nil)
    (org-lparse-insert-tag
     (if org-lparse-table-cur-rowgrp-is-hdr
	 "</table:table-header-rows>" "</table:table-rows>"))))

(defun org-odt-format-table-row (row)
  (org-odt-format-tags
   '("<table:table-row>" . "</table:table-row>") row))

(defun org-odt-get-style-name-for-table-cell (r c)
  (concat
   "OrgTblCell"
   (cond
    ((= r 0) "T")
    ((eq (cdr (assoc r org-lparse-table-rowgrp-info))  :start) "T")
    (t ""))
   (when (= r org-lparse-table-rownum) "B")
   (cond
    ((= c 0) "")
    ((or (memq (nth c org-table-colgroup-info) '(:start :startend))
	 (memq (nth (1- c) org-table-colgroup-info) '(:end :startend))) "L")
    (t ""))))

(defun org-odt-get-paragraph-style-for-table-cell (r c)
  (capitalize (aref org-lparse-table-colalign-vector c)))

(defun org-odt-format-table-cell (data r c)
  (if (not org-lparse-table-is-styled)
      (org-odt-format-tags
       '("<table:table-cell>" . "</table:table-cell>")
       (org-odt-format-stylized-paragraph
	(cond
	 (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
	 ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
	  "OrgTableHeading")
	 (t "OrgTableContents"))
	data))
    (let* ((style-name-cookie
	    (format "@@table-cell:style-name@@%03d@@%03d@@" r c))
	   (paragraph-style-cookie
	    (concat
	     (cond
	      (org-lparse-table-cur-rowgrp-is-hdr "OrgTableHeading")
	      ((and (= c 0) (org-lparse-get 'TABLE-FIRST-COLUMN-AS-LABELS))
	       "OrgTableHeading")
	      (t "OrgTableContents"))
	     (format "@@table-cell:p@@%03d@@%03d@@" r c))))
      (org-odt-format-tags
       '("<table:table-cell table:style-name=\"%s\">" .
	 "</table:table-cell>")
       (org-odt-format-stylized-paragraph paragraph-style-cookie data)
       style-name-cookie))))

(defun org-odt-begin-footnote-definition (n)
  (org-lparse-begin-paragraph 'footnote))

(defun org-odt-end-footnote-definition (n)
  (org-lparse-end-paragraph))

(defun org-odt-begin-toc (lang-specific-heading)
  (insert
   (format "
    <text:table-of-content text:style-name=\"Sect2\" text:protected=\"true\" text:name=\"Table of Contents1\">
     <text:table-of-content-source text:outline-level=\"10\">
      <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
" lang-specific-heading))

  (loop for level from 1 upto 10
	do (insert (format
		    "
      <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
       <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
       <text:index-entry-chapter/>
       <text:index-entry-text/>
       <text:index-entry-link-end/>
      </text:table-of-content-entry-template>
" level level)))

  (insert
   (format  "
     </text:table-of-content-source>

     <text:index-body>
      <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
       <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
      </text:index-title>
" lang-specific-heading)))

(defun org-odt-end-toc ()
  (insert "
     </text:index-body>
    </text:table-of-content>
"))

(defun org-odt-format-toc-entry (snumber todo headline tags href)
  (setq headline (concat
		  (and org-export-with-section-numbers
		       (concat snumber ". "))
		  headline
		  (and tags
		    (concat
		     (org-lparse-format 'SPACES 3)
		     (org-lparse-format 'FONTIFY tags "tag")))))
  (when todo
    (setq headline (org-lparse-format 'FONTIFY headline "todo")))

  (let ((org-odt-suppress-xref t))
    (org-odt-format-link headline (concat  "#" href))))

(defun org-odt-format-toc-item (toc-entry level org-last-level)
  (let ((style (format "Contents_20_%d"
		       (+ level (or (org-lparse-get 'TOPLEVEL-HLEVEL) 1) -1))))
    (insert "\n" (org-odt-format-stylized-paragraph style toc-entry) "\n")))

;; Following variable is let bound during 'ORG-LINK callback. See
;; org-html.el
(defvar org-lparse-link-description-is-image nil)
(defun org-odt-format-link (desc href &optional attr)
  (cond
   ((and (= (string-to-char href) ?#) (not org-odt-suppress-xref))
    (setq href (concat org-export-odt-bookmark-prefix (substring href 1)))
    (org-odt-format-tags
     '("<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"%s\">" .
       "</text:bookmark-ref>")
     desc href))
   (org-lparse-link-description-is-image
    (org-odt-format-tags
     '("<draw:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</draw:a>")
     desc href (or attr "")))
   (t
    (org-odt-format-tags
     '("<text:a xlink:type=\"simple\" xlink:href=\"%s\" %s>" . "</text:a>")
     desc href (or attr "")))))

(defun org-odt-format-spaces (n)
  (cond
   ((= n 1) " ")
   ((> n 1) (concat
	     " " (org-odt-format-tags "<text:s text:c=\"%d\"/>" "" (1- n))))
   (t "")))

(defun org-odt-format-tabs (&optional n)
  (let ((tab "<text:tab/>")
	(n (or n 1)))
    (insert tab)))

(defun org-odt-format-line-break ()
  (org-odt-format-tags "<text:line-break/>" ""))

(defun org-odt-format-horizontal-line ()
  (org-odt-format-stylized-paragraph 'horizontal-line ""))

(defun org-odt-format-line (line)
  (case org-lparse-dyn-current-environment
    (fixedwidth (concat
		 (org-odt-format-stylized-paragraph
		  'fixedwidth (org-odt-fill-tabs-and-spaces
			       (org-xml-encode-plain-text line))) "\n"))
    (t (concat line "\n"))))

(defun org-odt-format-comment (fmt &rest args)
  (let ((comment (apply 'format fmt args)))
    (format "\n<!-- %s  -->\n" comment)))

(defun org-odt-format-org-entity (wd)
  (org-entity-get-representation wd 'utf8))

(defun org-odt-fill-tabs-and-spaces (line)
  (replace-regexp-in-string
   "\\([\t]\\|\\([ ]+\\)\\)" (lambda (s)
			       (cond
				((string= s "\t") (org-odt-format-tabs))
				(t (org-odt-format-spaces (length s))))) line))

(defcustom org-export-odt-use-htmlfontify t
  "Specify whether or not source blocks need to be fontified.
Turn this option on if you want to colorize the source code
blocks in the exported file.  For colorization to work, you need
to make available an enhanced version of `htmlfontify' library."
  :type 'boolean
  :group 'org-export-odt)

(defun org-odt-format-source-code-or-example-plain
  (lines lang caption textareap cols rows num cont rpllbl fmt)
  "Format source or example blocks much like fixedwidth blocks.
Use this when `org-export-odt-use-htmlfontify' option is turned
off."
  (setq lines (org-export-number-lines (org-xml-encode-plain-text-lines lines)
				       0 0 num cont rpllbl fmt))
    (mapconcat
     (lambda (line)
       (org-odt-format-stylized-paragraph
	'fixedwidth (org-odt-fill-tabs-and-spaces line)))
     (org-split-string lines "[\r\n]") "\n"))

(defvar org-src-block-paragraph-format
  "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
   <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
    <style:background-image/>
   </style:paragraph-properties>
   <style:text-properties fo:color=\"%s\"/>
  </style:style>"
  "Custom paragraph style for colorized source and example blocks.
This style is much the same as that of \"OrgFixedWidthBlock\"
except that the foreground and background colors are set
according to the default face identified by the `htmlfontify'.")

(defun org-odt-hfy-face-to-css (fn)
  "Create custom style for face FN.
When FN is the default face, use it's foreground and background
properties to create \"OrgSrcBlock\" paragraph style.  Otherwise
use it's color attribute to create a character style whose name
is obtained from FN.  Currently all attributes of FN other than
color are ignored.

The style name for a face FN is derived using the following
operations on the face name in that order - de-dash, CamelCase
and prefix with \"OrgSrc\".  For example,
`font-lock-function-name-face' is associated with
\"OrgSrcFontLockFunctionNameFace\"."
  (let* ((css-list (hfy-face-to-style fn))
	 (style-name ((lambda (fn)
			(concat "OrgSrc"
				(mapconcat
				 'capitalize (split-string
					      (hfy-face-or-def-to-name fn) "-")
				 ""))) fn))
	 (color-val (cdr (assoc "color" css-list)))
	 (background-color-val (cdr (assoc "background" css-list)))
	 (style (and org-export-odt-create-custom-styles-for-srcblocks
		     (cond
		      ((eq fn 'default)
		       (format org-src-block-paragraph-format
			       background-color-val color-val))
		      (t
		       (format
			"
<style:style style:name=\"%s\" style:family=\"text\">
  <style:text-properties fo:color=\"%s\"/>
 </style:style>" style-name color-val))))))
    (cons style-name style)))

(defcustom org-export-odt-create-custom-styles-for-srcblocks t
  "Whether custom styles for colorized source blocks be automatically created.
When this option is turned on, the exporter creates custom styles
for source blocks based on the advice of `htmlfontify'.  Creation
of custom styles happen as part of `org-odt-hfy-face-to-css'.

When this option is turned off exporter does not create such
styles.

Use the latter option if you do not want the custom styles to be
based on your current display settings.  It is necessary that the
styles.xml already contains needed styles for colorizing to work.

This variable is effective only if
`org-export-odt-use-htmlfontify' is turned on."
  :group 'org-export-odt
  :type 'boolean)

(defun org-odt-insert-custom-styles-for-srcblocks (styles)
  "Save STYLES used for colorizing of source blocks.
Update styles.xml with styles that were collected as part of
`org-odt-hfy-face-to-css' callbacks."
  (when styles
    (with-current-buffer
	(find-file-noselect (expand-file-name "styles.xml") t)
      (goto-char (point-min))
      (when (re-search-forward "</office:styles>" nil t)
	(goto-char (match-beginning 0))
	(insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n")))))

(defun org-odt-format-source-code-or-example-colored
  (lines lang caption textareap cols rows num cont rpllbl fmt)
  "Format source or example blocks using `htmlfontify-string'.
Use this routine when `org-export-odt-use-htmlfontify' option is
turned on."
  (let* ((lang-m (and lang (or (cdr (assoc lang org-src-lang-modes)) lang)))
	 (mode (and lang-m (intern (concat (if (symbolp lang-m)
					       (symbol-name lang-m)
					     lang-m) "-mode"))))
	 (org-inhibit-startup t)
	 (org-startup-folded nil)
	 (lines (with-temp-buffer
		  (insert lines)
		  (if (functionp mode) (funcall mode) (fundamental-mode))
		  (font-lock-fontify-buffer)
		  (buffer-string)))
	 (hfy-html-quote-regex "\\([<\"&> 	]\\)")
	 (hfy-html-quote-map '(("\"" "&quot;")
			       ("<" "&lt;")
			       ("&" "&amp;")
			       (">" "&gt;")
			       (" " "<text:s/>")
			       ("	" "<text:tab/>")))
	 (hfy-face-to-css 'org-odt-hfy-face-to-css)
	 (hfy-optimisations-1 (copy-seq hfy-optimisations))
	 (hfy-optimisations (add-to-list 'hfy-optimisations-1
					 'body-text-only))
	 (hfy-begin-span-handler
	  (lambda (style text-block text-id text-begins-block-p)
	    (insert (format "<text:span text:style-name=\"%s\">" style))))
	 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
    (when (fboundp 'htmlfontify-string)
      (mapconcat
       (lambda (line)
	 (org-odt-format-stylized-paragraph 'src (htmlfontify-string line)))
       (org-split-string lines "[\r\n]") "\n"))))

(defun org-odt-format-source-code-or-example (lines lang caption textareap
						    cols rows num cont
						    rpllbl fmt)
  "Format source or example blocks for export.
Use `org-odt-format-source-code-or-example-plain' or
`org-odt-format-source-code-or-example-colored' depending on the
value of `org-export-odt-use-htmlfontify."
  (funcall
   (if (and org-export-odt-use-htmlfontify
	    (or (featurep 'htmlfontify) (require 'htmlfontify))
	    (fboundp 'htmlfontify-string))
       'org-odt-format-source-code-or-example-colored
     'org-odt-format-source-code-or-example-plain)
   lines lang caption textareap cols rows num cont rpllbl fmt))

(defun org-xml-encode-plain-text-lines (rtn)
  (mapconcat 'org-xml-encode-plain-text (org-split-string rtn "[\r\n]") "\n"))

(defun org-odt-remap-stylenames (style-name)
  (or
   (cdr (assoc style-name '(("timestamp-wrapper" . "OrgTimestampWrapper")
			    ("timestamp" . "OrgTimestamp")
			    ("timestamp-kwd" . "OrgTimestampKeyword")
			    ("tag" . "OrgTag")
			    ("todo" . "OrgTodo")
			    ("done" . "OrgDone")
			    ("target" . "OrgTarget"))))
   style-name))

(defun org-odt-format-fontify (text style &optional id)
  (let* ((style-name
	  (cond
	   ((stringp style)
	    (org-odt-remap-stylenames style))
	   ((symbolp style)
	    (org-odt-get-style-name-for-entity 'character style))
	   ((listp style)
	    (assert (< 1 (length style)))
	    (let ((parent-style (pop style)))
	      (mapconcat (lambda (s)
			   ;; (assert (stringp s) t)
			   (org-odt-remap-stylenames s)) style "")
	      (org-odt-remap-stylenames parent-style)))
	   (t (error "Don't how to handle style %s"  style)))))
    (org-odt-format-tags
     '("<text:span text:style-name=\"%s\">" . "</text:span>")
     text style-name)))

(defun org-odt-relocate-relative-path (path dir)
  (if (file-name-absolute-p path) path
    (file-relative-name (expand-file-name path dir)
			(expand-file-name "eyecandy" dir))))

(defun org-odt-format-inline-image (thefile)
  (let* ((thelink (if (file-name-absolute-p thefile) thefile
		    (org-xml-format-href
		     (org-odt-relocate-relative-path
		      thefile org-current-export-file))))
	 (href
	  (org-odt-format-tags
	   "<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>" ""
	   (if org-export-odt-embed-images
	       (org-odt-copy-image-file thefile) thelink))))
    (org-export-odt-format-image thefile href)))

(defun org-odt-format-org-link (opt-plist type-1 path fragment desc attr
					  descp)
  "Make an HTML link.
OPT-PLIST is an options list.
TYPE is the device-type of the link (THIS://foo.html)
PATH is the path of the link (http://THIS#locationx)
FRAGMENT is the fragment part of the link, if any (foo.html#THIS)
DESC is the link description, if any.
ATTR is a string of other attributes of the a element.
MAY-INLINE-P allows inlining it as an image."

  (declare (special org-lparse-par-open))
  (save-match-data
    (let* ((may-inline-p
	    (and (member type-1 '("http" "https" "file"))
		 (org-lparse-should-inline-p path descp)
		 (not fragment)))
	   (type (if (equal type-1 "id") "file" type-1))
	   (filename path)
	   (thefile path))

      (cond
       ;; check for inlined images
       ((and (member type '("file"))
	     (not fragment)
	     (org-file-image-p
	      filename org-odt-export-inline-image-extensions)
	     (or (eq t org-odt-export-inline-images)
		 (and org-odt-export-inline-images (not descp))))

	;; (when (and (string= type "file") (file-name-absolute-p path))
	;;   (setq thefile (concat "file://" (expand-file-name path))))
	;; (setq thefile (org-xml-format-href thefile))
	;; (org-export-html-format-image thefile)
	(org-odt-format-inline-image thefile))
       (t
	(when (string= type "file")
	  (setq thefile
		(cond
		 ((file-name-absolute-p path)
		  (concat "file://" (expand-file-name path)))
		 (t (org-odt-relocate-relative-path
		     thefile org-current-export-file)))))

	(when (and (member type '("" "http" "https" "file" "coderef"))
		   fragment)
	  (setq thefile (concat thefile "#" fragment)))

	(setq thefile (org-xml-format-href thefile))

	(when (not (member type '("" "file" "coderef")))
	  (setq thefile (concat type ":" thefile)))

	(let ((org-odt-suppress-xref (string= type "coderef")))
	  (org-odt-format-link
	   (org-xml-format-desc desc) thefile attr)))))))

(defun org-odt-format-heading (text level &optional id)
  (let* ((text (if id (org-odt-format-target text id) text)))
    (org-odt-format-tags
     '("<text:h text:style-name=\"Heading_20_%s\" text:outline-level=\"%s\">" .
       "</text:h>") text level level)))

(defun org-odt-format-headline (title extra-targets tags
					    &optional snumber level)
  (concat
   (org-lparse-format 'EXTRA-TARGETS extra-targets)

   ;; No need to generate section numbers. They are auto-generated by
   ;; the application

   ;; (concat (org-lparse-format 'SECTION-NUMBER snumber level) " ")
   title
   (and tags (concat (org-lparse-format 'SPACES 3)
		     (org-lparse-format 'ORG-TAGS tags)))))

(defun org-odt-format-anchor (text name &optional class)
  (org-odt-format-target text name))

(defun org-odt-format-bookmark (text id)
  (if id
      (org-odt-format-tags "<text:bookmark text:name=\"%s\"/>" text id)
    text))

(defun org-odt-format-target (text id)
  (let ((name (concat org-export-odt-bookmark-prefix id)))
    (concat
     (and id (org-odt-format-tags
	      "<text:bookmark-start text:name=\"%s\"/>" "" name))
     (org-odt-format-bookmark text id)
     (and id (org-odt-format-tags
	      "<text:bookmark-end text:name=\"%s\"/>" "" name)))))

(defun org-odt-format-footnote (n def)
  (let ((id (concat  "fn" n))
	(note-class "footnote")
	(par-style "Footnote"))
    (org-odt-format-tags
     '("<text:note text:id=\"%s\" text:note-class=\"%s\">" .
       "</text:note>")
     (concat
      (org-odt-format-tags
       '("<text:note-citation>" . "</text:note-citation>")
       n)
      (org-odt-format-tags
       '("<text:note-body>" . "</text:note-body>")
       def))
     id note-class)))

(defun org-odt-format-footnote-reference (n def refcnt)
  (if (= refcnt 1)
      (org-odt-format-footnote n def)
    (org-odt-format-footnote-ref n)))

(defun org-odt-format-footnote-ref (n)
  (let ((note-class "footnote")
	(ref-format "text")
	(ref-name (concat "fn" n)))
    (org-odt-format-tags
     '("<text:span text:style-name=\"%s\">" . "</text:span>")
     (org-odt-format-tags
      '("<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">" . "</text:note-ref>")
      n note-class ref-format ref-name)
     "OrgSuperscript")))

(defun org-odt-get-image-name (file-name)
  (require 'sha1)
  (file-relative-name
   (expand-file-name
    (concat (sha1 file-name) "." (file-name-extension file-name)) "Pictures")))

(defun org-export-odt-format-image (src href)
  "Create image tag with source and attributes."
  (save-match-data
    (let* ((caption (org-find-text-property-in-string 'org-caption src))
	   (caption (and caption (org-xml-format-desc caption)))
	   (attr (org-find-text-property-in-string 'org-attributes src))
	   (label (org-find-text-property-in-string 'org-label src))
	   (embed-as (if (string-match "^ltxpng/" src) 'character 'paragraph))
	   (attr-plist (when attr (read  attr)))
	   (size (org-odt-image-size-from-file
		  src (plist-get attr-plist :width)
		  (plist-get attr-plist :height)
		  (plist-get attr-plist :scale) nil embed-as)))
      (org-export-odt-do-format-image
       embed-as caption attr label size href))))

(defun org-odt-format-textbox (text style)
  (let ((draw-frame-pair
	 '("<draw:frame draw:style-name=\"%s\"
              text:anchor-type=\"paragraph\"
              style:rel-width=\"100%%\"
              draw:z-index=\"0\">" . "</draw:frame>")))
    (org-odt-format-tags
     draw-frame-pair
     (org-odt-format-tags
      '("<draw:text-box fo:min-height=\"%dcm\">" . "</draw:text-box>")
      text 0) style)))

(defun org-odt-format-inlinetask (heading content
					  &optional todo priority tags)
  (org-odt-format-stylized-paragraph
   nil (org-odt-format-textbox
	(concat (org-odt-format-stylized-paragraph
		 "OrgInlineTaskHeading"
		 (org-lparse-format
		  'HEADLINE (concat (org-lparse-format-todo todo) " " heading)
		  nil tags))
		content) "OrgInlineTaskFrame")))

(defun org-export-odt-do-format-image (embed-as caption attr label
						size href)
  "Create image tag with source and attributes."
  (save-match-data
    (let ((width (car size)) (height (cdr size))
	  (draw-frame-pair
	   '("<draw:frame draw:style-name=\"%s\"
              text:anchor-type=\"%s\"
              draw:z-index=\"%d\" %s>" . "</draw:frame>")))
      (cond
       ((and (not caption) (not label))
	(let (style-name anchor-type)
	  (cond
	   ((eq embed-as 'paragraph)
	    (setq style-name  "OrgGraphicsParagraph" anchor-type "paragraph"))
	   ((eq embed-as 'character)
	    (setq style-name  "OrgGraphicsBaseline" anchor-type "as-char")))
	  (org-odt-format-tags
	   draw-frame-pair href style-name anchor-type 0
	   (org-odt-image-attrs-from-size width height))))

       (t
	(concat
	 ;; (when par-open (org-odt-close-par))
	 (org-odt-format-tags
	  draw-frame-pair
	  (org-odt-format-tags
	   '("<draw:text-box fo:min-height=\"%dcm\">" . "</draw:text-box>")
	   (org-odt-format-stylized-paragraph
	    'illustration
	    (concat
	     (let ((extra " style:rel-width=\"100%\" style:rel-height=\"scale\""))
	       (org-odt-format-tags
		draw-frame-pair href "OrgGraphicsParagraphContent" "paragraph" 2
		(concat (org-odt-image-attrs-from-size width height) extra)))
	     (org-odt-format-entity-caption label caption)))
	   height)
	  "OrgFrame" "paragraph" 1
	  (org-odt-image-attrs-from-size width))

	 ;; (when par-open (org-odt-open-par))
	 ))))))

;; xml files generated on-the-fly
(defconst org-export-odt-save-list
  '("mimetype" "META-INF/manifest.xml" "content.xml" "meta.xml" "styles.xml"))

;; xml files that are copied
(defconst org-export-odt-nosave-list '())

;; xml files that contribute to the final odt file
(defvar org-export-odt-file-list nil)

(defconst org-export-odt-manifest-lines
  '(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
     "<manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">"
     "<manifest:file-entry manifest:media-type=\"application/vnd.oasis.opendocument.text\" manifest:version=\"1.2\" manifest:full-path=\"/\"/>"
     "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"content.xml\"/>"
     "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"styles.xml\"/>"
     "<manifest:file-entry manifest:media-type=\"text/xml\" manifest:full-path=\"meta.xml\"/>"
     "<manifest:file-entry manifest:media-type=\"\" manifest:full-path=\"Pictures/\"/>") . ("</manifest:manifest>")))

(defconst org-export-odt-meta-lines
  '(("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
     "<office:document-meta"
     "    xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\""
     "    xmlns:xlink=\"http://www.w3.org/1999/xlink\""
     "    xmlns:dc=\"http://purl.org/dc/elements/1.1/\""
     "    xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\""
     "    xmlns:ooo=\"http://openoffice.org/2004/office\" "
     "    office:version=\"1.2\">"
     "  <office:meta>") . ("  </office:meta>" "</office:document-meta>")))

(defun org-odt-copy-image-file (path &optional target-file)
  "Returns the internal name of the file"
  (let* ((image-type (file-name-extension path))
	 (media-type (format "image/%s" image-type))
	 (src-file (expand-file-name
		    path (file-name-directory org-current-export-file)))
	 (target-file (or target-file (org-odt-get-image-name src-file)))
	 ;; FIXME
	 (body-only nil))

    (when (not org-lparse-to-buffer)
      (message "Embedding %s as %s ..."
	       (substring-no-properties path) target-file)
      (copy-file src-file target-file 'overwrite)
      (org-odt-update-manifest-file media-type target-file)
      (push target-file org-export-odt-file-list)) target-file))

(defun org-odt-image-attrs-from-size (&optional width height)
  (concat
   (when width (format "svg:width=\"%0.2fcm\""  width))
   " "
   (when height (format "svg:height=\"%0.2fcm\""  height))))

(defvar org-export-odt-image-size-probe-method
  '(emacs imagemagick force)
  "Ordered list of methods by for determining size of an embedded
  image.")

(defvar org-export-odt-default-image-sizes-alist
  '(("character" . (5 . 0.4))
    ("paragraph" . (5 . 5)))
  "Hardcoded image dimensions one for each of the anchor
  methods.")

(defun org-odt-do-image-size (probe-method file &optional dpi anchor-type)
  (setq dpi (or dpi org-export-odt-pixels-per-inch))
  (setq anchor-type (or anchor-type "paragraph"))
  (flet ((size-in-cms (size-in-pixels)
		      (flet ((pixels-to-cms (pixels)
					    (let* ((cms-per-inch 2.54)
						   (inches (/ pixels dpi)))
					      (* cms-per-inch inches))))
			(and size-in-pixels
			     (cons (pixels-to-cms (car size-in-pixels))
				   (pixels-to-cms (cdr size-in-pixels)))))))
    (case probe-method
      (emacs
       (size-in-cms (ignore-errors (image-size (create-image file) 'pixels))))
      (imagemagick
       (size-in-cms
	(let ((dim (shell-command-to-string
		    (format "identify -format \"%%w:%%h\" \"%s\"" file))))
	  (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
	    (cons (string-to-number (match-string 1 dim))
		  (string-to-number (match-string 2 dim)))))))
      (t
       (cdr (assoc-string anchor-type
			  org-export-odt-default-image-sizes-alist))))))

(defun org-odt-image-size-from-file (file &optional user-width
					  user-height scale dpi embed-as)
  (unless (file-name-absolute-p file)
    (setq file (expand-file-name
		file (file-name-directory org-current-export-file))))
  (let* (size width height)
    (unless (and user-height user-width)
      (loop for probe-method in org-export-odt-image-size-probe-method
	    until size
	    do (setq size (org-odt-do-image-size
			   probe-method file dpi embed-as)))
      (or size (error "Cannot determine Image size. Aborting ..."))
      (setq width (car size) height (cdr size)))
    (cond
     (scale
      (setq width (* width scale) height (* height scale)))
     ((and user-height user-width)
      (setq width user-width height user-height))
     (user-height
      (setq width (* user-height (/ width height)) height user-height))
     (user-width
      (setq height (* user-width (/ height width)) width user-width))
     (t (ignore)))
    (cons width height)))

(defvar org-odt-default-entity "Illustration")
(defun org-odt-format-entity-caption (label caption &optional default-entity)
  (if (not label) (or caption "")
    (let* ((label-components (org-odt-parse-label label))
	   (entity (car label-components))
	   (seqno (cdr label-components))
	   (caption (and caption (concat ": " caption))))
      (unless seqno
	(setq seqno label
	      entity (or default-entity org-odt-default-entity)))
      (concat
       entity " "
       (org-odt-format-tags
	'("<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">" . "</text:sequence>")
	seqno label entity entity)
       caption))))

(defun org-odt-format-tags (tag text &rest args)
  (let ((prefix (when org-lparse-encode-pending "@"))
	(suffix (when org-lparse-encode-pending "@")))
    (apply 'org-lparse-format-tags tag text prefix suffix args)))

(defun org-odt-init-outfile (filename)
  (unless (executable-find "zip")
    ;; Not at all OSes ship with zip by default
    (error "Executable \"zip\" needed for creating OpenDocument files. Aborting."))

  (let* ((outdir (make-temp-file org-export-odt-tmpdir-prefix t))
	 (mimetype-file (expand-file-name "mimetype" outdir))
	 (content-file (expand-file-name "content.xml" outdir))
	 (manifest-file (expand-file-name "META-INF/manifest.xml" outdir))
	 (meta-file (expand-file-name "meta.xml" outdir))
	 (styles-file (expand-file-name "styles.xml" outdir))
	 (pictures-dir (expand-file-name "Pictures" outdir))
	 (body-only nil))

    ;; content file
    (with-current-buffer (find-file-noselect content-file t)
      (erase-buffer))

    ;; FIXME: How to factor in body-only here
    (unless body-only
      ;; manifest file
      (make-directory (file-name-directory manifest-file))
      (with-current-buffer (find-file-noselect manifest-file t)
	(erase-buffer)
	(insert (mapconcat 'identity (car org-export-odt-manifest-lines) "\n"))
	(insert "\n")
	(save-excursion
	  (insert (mapconcat 'identity (cdr org-export-odt-manifest-lines) "\n"))))

    ;; meta file
    (with-current-buffer (find-file-noselect meta-file t)
      (erase-buffer)
      (insert (mapconcat 'identity (car org-export-odt-meta-lines) "\n"))
      (insert "\n")
      (save-excursion
	(insert (mapconcat 'identity (cdr org-export-odt-meta-lines) "\n"))))

    ;; mimetype
    (with-current-buffer (find-file-noselect mimetype-file t)
      (insert "application/vnd.oasis.opendocument.text"))

    ;; styles file
    ;; (copy-file org-export-odt-styles-file styles-file t)

    ;; Pictures dir
    (make-directory pictures-dir)

    ;; initialize list of files that contribute to the odt file
    (setq org-export-odt-file-list
	  (append org-export-odt-save-list org-export-odt-nosave-list)))
    content-file))

(defconst org-odt-manifest-file-entry-tag
  "<manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"/>")

(defcustom org-export-odt-prettify-xml nil
  "Specify whether or not the xml output should be prettified.
When this option is turned on, `indent-region' is run on all
component xml buffers before they are saved.  Turn this off for
regular use.  Turn this on if you need to examine the xml
visually."
  :group 'org-export-odt
  :type 'boolean)

(defvar hfy-user-sheet-assoc)		; bound during org-do-lparse
(defun org-odt-save-as-outfile (target opt-plist)
  ;; write meta file
  (org-odt-update-meta-file opt-plist)

  ;; write styles file
  (org-odt-copy-styles-file)

  ;; Update styles.xml - take care of outline numbering
  (with-current-buffer
      (find-file-noselect (expand-file-name "styles.xml") t)
    ;; Don't make automatic backup of styles.xml file. This setting
    ;; prevents the backedup styles.xml file from being zipped in to
    ;; odt file. This is more of a hackish fix. Better alternative
    ;; would be to fix the zip command so that the output odt file
    ;; includes only the needed files and excludes any auto-generated
    ;; extra files like backups and auto-saves etc etc. Note that
    ;; currently the zip command zips up the entire temp directory so
    ;; that any auto-generated files created under the hood ends up in
    ;; the resulting odt file.
    (set (make-local-variable 'backup-inhibited) t)

    ;; Import local setting of `org-export-with-section-numbers'
    (org-lparse-bind-local-variables opt-plist)
    (org-odt-configure-outline-numbering
     (if org-export-with-section-numbers org-export-headline-levels 0)))

  ;; Write custom stlyes for source blocks
  (org-odt-insert-custom-styles-for-srcblocks
   (mapconcat
    (lambda (style)
      (format " %s\n" (cddr style)))
    hfy-user-sheet-assoc ""))

  (let ((zipdir default-directory))
    (message "Switching to directory %s" (expand-file-name zipdir))

    ;; save all xml files
    (mapc (lambda (file)
	    (with-current-buffer
		(find-file-noselect (expand-file-name file) t)
	      ;; prettify output if needed
	      (when org-export-odt-prettify-xml
		(indent-region (point-min) (point-max)))
	      (save-buffer)))
	  org-export-odt-save-list)

    (let* ((target-name (file-name-nondirectory target))
	   (target-dir (file-name-directory target))
	   (cmds `(("zip" "-mX0" ,target-name "mimetype")
		   ("zip" "-rmTq" ,target-name "."))))
      (when (file-exists-p target)
	;; FIXME: If the file is locked this throws a cryptic error
	(delete-file target))

      (let ((coding-system-for-write 'no-conversion) exitcode)
	(message "Creating odt file...")
	(mapc
	 (lambda (cmd)
	   (message "Running %s" (mapconcat 'identity cmd " "))
	   (setq exitcode
		 (apply 'call-process (car cmd) nil nil nil (cdr cmd)))
	   (or (zerop exitcode)
	       (error "Unable to create odt file (%S)" exitcode)))
	 cmds))

      ;; move the file from outdir to target-dir
      (rename-file target-name target-dir)

      ;; kill all xml buffers
      (mapc (lambda (file)
	      (kill-buffer
	       (find-file-noselect (expand-file-name file zipdir) t)))
	    org-export-odt-save-list)

      (delete-directory zipdir)))

  (message "Created %s" target)
  (set-buffer (find-file-noselect target t)))

(defun org-odt-format-date (date)
  (let ((warning-msg
	 "OpenDocument files require that dates be in ISO-8601 format. Please review your DATE options for compatibility."))
    ;; If the user is not careful with the date specification, an
    ;; invalid meta.xml will be emitted.

    ;; For now honor user's diktat and let him off with a warning
    ;; message. This is OK as LibreOffice (and possibly other
    ;; apps) doesn't deem this deviation as critical and continue
    ;; to load the file.

    ;; FIXME: Surely there a better way to handle this. Revisit this
    ;; later.
    (cond
     ((and date (string-match "%" date))
      ;; Honor user's diktat. See comments above
      (org-lparse-warn warning-msg)
      (format-time-string date))
     (date
      ;; Honor user's diktat. See comments above
      (org-lparse-warn warning-msg)
      date)
     (t
      ;; ISO 8601 format
      (format-time-string "%Y-%m-%dT%T%:z")))))

(defun org-odt-update-meta-file (opt-plist)
  (with-current-buffer
      (find-file-noselect (expand-file-name "meta.xml") t)
    (let ((date (org-odt-format-date (plist-get opt-plist :date)))
	  (author (or (plist-get opt-plist :author) ""))
	  (email (plist-get opt-plist :email))
	  (keywords (plist-get opt-plist :keywords))
	  (description (plist-get opt-plist :description))
	  (title (plist-get opt-plist :title)))

      (insert
       "\n"
       (org-odt-format-tags '("<dc:creator>" . "</dc:creator>") author)
       (org-odt-format-tags
	'("\n<meta:initial-creator>" . "</meta:initial-creator>") author)
       (org-odt-format-tags '("\n<dc:date>" . "</dc:date>") date)
       (org-odt-format-tags
	'("\n<meta:creation-date>" . "</meta:creation-date>") date)
       (org-odt-format-tags '("\n<meta:generator>" . "</meta:generator>")
			     (when org-export-creator-info
			       (format "Org-%s/Emacs-%s"
				       org-version emacs-version)))
       (org-odt-format-tags '("\n<meta:keyword>" . "</meta:keyword>") keywords)
       (org-odt-format-tags '("\n<dc:subject>" . "</dc:subject>") description)
       (org-odt-format-tags '("\n<dc:title>" . "</dc:title>") title)
       "\n"))))

(defun org-odt-update-manifest-file (media-type full-path)
  (with-current-buffer
      (find-file-noselect (expand-file-name "META-INF/manifest.xml") t)
    (insert (format org-odt-manifest-file-entry-tag media-type full-path))))

(defun org-odt-finalize-outfile ()
  (org-odt-delete-empty-paragraphs))

(defun org-odt-delete-empty-paragraphs ()
  (goto-char (point-min))
  (let ((open "<text:p[^>]*>")
	(close "</text:p>"))
    (while (re-search-forward (format "%s[ \r\n\t]*%s" open close) nil t)
      (replace-match ""))))

(defun org-odt-get (what &optional opt-plist)
  (case what
    (BACKEND 'odt)
    (EXPORT-DIR (org-export-directory :html opt-plist))
    (FILE-NAME-EXTENSION "odt")
    (EXPORT-BUFFER-NAME "*Org ODT Export*")
    (ENTITY-CONTROL org-odt-entity-control-callbacks-alist)
    (ENTITY-FORMAT org-odt-entity-format-callbacks-alist)
    (INIT-METHOD 'org-odt-init-outfile)
    (FINAL-METHOD 'org-odt-finalize-outfile)
    (SAVE-METHOD 'org-odt-save-as-outfile)
    ;; (OTHER-BACKENDS)			; see note in `org-xhtml-get'
    ;; (CONVERT-METHOD)			; see note in `org-xhtml-get'
    (TOPLEVEL-HLEVEL 1)
    (SPECIAL-STRING-REGEXPS org-export-odt-special-string-regexps)
    (INLINE-IMAGES 'maybe)
    (INLINE-IMAGE-EXTENSIONS '("png" "jpeg" "jpg" "gif" "svg"))
    (PLAIN-TEXT-MAP '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
    (TABLE-FIRST-COLUMN-AS-LABELS nil)
    (FOOTNOTE-SEPARATOR (org-lparse-format 'FONTIFY "," 'superscript))
    (CODING-SYSTEM-FOR-WRITE 'utf-8)
    (CODING-SYSTEM-FOR-SAVE 'utf-8)
    (t (error "Unknown property: %s"  what))))

(defun org-odt-parse-label (label)
  (save-match-data
    (if (not (string-match "\\`[a-zA-Z]+:\\(.+\\)" label))
	(cons label nil)
      (cons
       (capitalize (substring label 0 (1- (match-beginning 1))))
       (substring label (match-beginning 1))))))

(defvar org-lparse-latex-fragment-fallback) ; set by org-do-lparse
(defvar org-lparse-opt-plist)		    ; bound during org-do-lparse
(defun org-export-odt-do-preprocess-latex-fragments ()
  "Convert LaTeX fragments to images."
  (let* ((latex-frag-opt (plist-get org-lparse-opt-plist :LaTeX-fragments))
	 (latex-frag-opt-1		;  massage the options
	  (or (and (member latex-frag-opt '(mathjax t))
		   (prog1 org-lparse-latex-fragment-fallback
		     (org-lparse-warn
		      (concat
		       "Use of MathJax is incompatible with ODT exporter. "
		       (format "Using %S instead."
			       org-lparse-latex-fragment-fallback)))))
	      latex-frag-opt)))
    (when (and org-current-export-file latex-frag-opt-1)
      ;; Investigate MathToWeb for converting TeX equations to MathML
      ;; http://lists.gnu.org/archive/html/emacs-orgmode/2011-03/msg01755.html
      (org-format-latex
       (concat "ltxpng/" (file-name-sans-extension
			  (file-name-nondirectory
			   org-current-export-file)))
       org-current-export-dir nil "Creating LaTeX image %s"
       nil nil latex-frag-opt-1))))

(defun org-export-odt-preprocess-latex-fragments ()
  (when (equal org-export-current-backend 'odt)
    (org-export-odt-do-preprocess-latex-fragments)))

(defun org-export-odt-preprocess-label-references ()
  (goto-char (point-min))
  (let (label label-components category value pretty-label)
    (while (re-search-forward "\\\\ref{\\([^{}\n]+\\)}" nil t)
      (org-if-unprotected-at (match-beginning 1)
	(setq label (match-string 1)
	      label-components (org-odt-parse-label label)
	      category (car label-components)
	      value (cdr label-components)
	      pretty-label (if value (concat category " " value) label))
	(replace-match
	 (let ((org-lparse-encode-pending t))
	   (org-odt-format-tags
	    '("<text:sequence-ref text:reference-format=\"category-and-value\" text:ref-name=\"%s\">"
	      . "</text:sequence-ref>") pretty-label label)) t t)))))

;; process latex fragments as part of
;; `org-export-preprocess-after-blockquote-hook'. Note that this hook
;; is the one that is closest and well before the call to
;; `org-export-attach-captions-and-attributes' in
;; `org-export-preprocess-stirng'.  The above arrangement permits
;; captions, labels and attributes to be attached to png images
;; generated out of latex equations.
(add-hook 'org-export-preprocess-after-blockquote-hook
	  'org-export-odt-preprocess-latex-fragments)

(defun org-export-odt-preprocess (parameters)
  (org-export-odt-preprocess-label-references))

(declare-function archive-zip-extract "arc-mode.el" (archive name))
(defun org-odt-zip-extract-one (archive member &optional target)
  (require 'arc-mode)
  (let* ((target (or target default-directory))
	 (archive (expand-file-name archive))
	 (archive-zip-extract
	  (list "unzip" "-qq" "-o" "-d" target))
	 exit-code command-output)
    (setq command-output
	  (with-temp-buffer
	    (setq exit-code (archive-zip-extract archive member))
	    (buffer-string)))
    (unless (zerop exit-code)
      (message command-output)
      (error "Extraction failed"))))

(defun org-odt-zip-extract (archive members &optional target)
  (when (atom members) (setq members (list members)))
  (mapc (lambda (member)
	  (org-odt-zip-extract-one archive member target))
	members))

(defun org-odt-copy-styles-file (&optional styles-file)
  ;; Non-availability of styles.xml is not a critical error. For now
  ;; throw an error purely for aesthetic reasons.
  (setq styles-file (or styles-file
			org-export-odt-styles-file
			(expand-file-name "styles/OrgOdtStyles.xml"
					  org-odt-data-dir)
			(error "org-odt: Missing styles file?")))
  (cond
   ((listp styles-file)
    (let ((archive (nth 0 styles-file))
	  (members (nth 1 styles-file)))
      (org-odt-zip-extract archive members)
      (mapc
       (lambda (member)
	 (when (org-file-image-p member)
	   (let* ((image-type (file-name-extension member))
		  (media-type (format "image/%s" image-type)))
	     (org-odt-update-manifest-file media-type member))))
       members)))
   ((and (stringp styles-file) (file-exists-p styles-file))
    (let ((styles-file-type (file-name-extension styles-file)))
      (cond
       ((string= styles-file-type "xml")
	(copy-file styles-file "styles.xml" t))
       ((member styles-file-type '("odt" "ott"))
	(org-odt-zip-extract styles-file "styles.xml")))))
   (t
    (error (format "Invalid specification of styles.xml file: %S"
		   org-export-odt-styles-file)))))

(defvar org-export-odt-factory-settings
  "d4328fb9d1b6cb211d4320ff546829f26700dc5e"
  "SHA1 hash of OrgOdtStyles.xml.")

(defun org-odt-configure-outline-numbering (level)
  "Outline numbering is retained only upto LEVEL.
To disable outline numbering pass a LEVEL of 0."
  (goto-char (point-min))
  (let ((regex
	 "<text:outline-level-style\\(.*\\)text:level=\"\\([^\"]*\\)\"\\(.*\\)>")
	(replacement
	 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
    (while (re-search-forward regex nil t)
      (when (> (string-to-number (match-string 2)) level)
	(replace-match replacement t nil))))
  (save-buffer 0))

(provide 'org-odt)

;;; org-odt.el ends here

debug log:

solving a5b2d96 ...
found a5b2d96 in https://git.savannah.gnu.org/cgit/emacs/org-mode.git

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

Code repositories for project(s) associated with this public inbox

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

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).