Revert "ox-odt.el: Fix annotation insertion."
[org-mode.git] / lisp / ox-odt.el
blob9dd8946087132d251cbb42324f1da00e7352fbba
1 ;;; ox-odt.el --- OpenDocument Text Exporter for Org Mode
3 ;; Copyright (C) 2010-2013 Free Software Foundation, Inc.
5 ;; Author: Jambunathan K <kjambunathan at gmail dot com>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;;; Code:
28 (eval-when-compile
29 (require 'cl)
30 (require 'table))
31 (require 'format-spec)
32 (require 'ox)
33 (require 'org-compat)
35 ;;; Define Back-End
37 (org-export-define-backend 'odt
38 '((bold . org-odt-bold)
39 (center-block . org-odt-center-block)
40 (clock . org-odt-clock)
41 (code . org-odt-code)
42 (drawer . org-odt-drawer)
43 (dynamic-block . org-odt-dynamic-block)
44 (entity . org-odt-entity)
45 (example-block . org-odt-example-block)
46 (export-block . org-odt-export-block)
47 (export-snippet . org-odt-export-snippet)
48 (fixed-width . org-odt-fixed-width)
49 (footnote-definition . org-odt-footnote-definition)
50 (footnote-reference . org-odt-footnote-reference)
51 (headline . org-odt-headline)
52 (horizontal-rule . org-odt-horizontal-rule)
53 (inline-src-block . org-odt-inline-src-block)
54 (inlinetask . org-odt-inlinetask)
55 (italic . org-odt-italic)
56 (item . org-odt-item)
57 (keyword . org-odt-keyword)
58 (latex-environment . org-odt-latex-environment)
59 (latex-fragment . org-odt-latex-fragment)
60 (line-break . org-odt-line-break)
61 (link . org-odt-link)
62 (paragraph . org-odt-paragraph)
63 (plain-list . org-odt-plain-list)
64 (plain-text . org-odt-plain-text)
65 (planning . org-odt-planning)
66 (property-drawer . org-odt-property-drawer)
67 (quote-block . org-odt-quote-block)
68 (quote-section . org-odt-quote-section)
69 (radio-target . org-odt-radio-target)
70 (section . org-odt-section)
71 (special-block . org-odt-special-block)
72 (src-block . org-odt-src-block)
73 (statistics-cookie . org-odt-statistics-cookie)
74 (strike-through . org-odt-strike-through)
75 (subscript . org-odt-subscript)
76 (superscript . org-odt-superscript)
77 (table . org-odt-table)
78 (table-cell . org-odt-table-cell)
79 (table-row . org-odt-table-row)
80 (target . org-odt-target)
81 (template . org-odt-template)
82 (timestamp . org-odt-timestamp)
83 (underline . org-odt-underline)
84 (verbatim . org-odt-verbatim)
85 (verse-block . org-odt-verse-block))
86 :export-block "ODT"
87 :filters-alist '((:filter-parse-tree
88 . (org-odt--translate-latex-fragments
89 org-odt--translate-description-lists
90 org-odt--translate-list-tables)))
91 :menu-entry
92 '(?o "Export to ODT"
93 ((?o "As ODT file" org-odt-export-to-odt)
94 (?O "As ODT file and open"
95 (lambda (a s v b)
96 (if a (org-odt-export-to-odt t s v)
97 (org-open-file (org-odt-export-to-odt nil s v) 'system))))))
98 :options-alist
99 '((:odt-styles-file "ODT_STYLES_FILE" nil nil t)
100 ;; Redefine regular option.
101 (:with-latex nil "tex" org-odt-with-latex)))
104 ;;; Dependencies
106 ;;; Hooks
108 ;;; Function Declarations
110 (declare-function org-id-find-id-file "org-id" (id))
111 (declare-function hfy-face-to-style "htmlfontify" (fn))
112 (declare-function hfy-face-or-def-to-name "htmlfontify" (fn))
113 (declare-function archive-zip-extract "arc-mode" (archive name))
114 (declare-function org-create-math-formula "org" (latex-frag &optional mathml-file))
115 (declare-function browse-url-file-url "browse-url" (file))
119 ;;; Internal Variables
121 (defconst org-odt-lib-dir
122 (file-name-directory load-file-name)
123 "Location of ODT exporter.
124 Use this to infer values of `org-odt-styles-dir' and
125 `org-odt-schema-dir'.")
127 (defvar org-odt-data-dir
128 (expand-file-name "../../etc/" org-odt-lib-dir)
129 "Data directory for ODT exporter.
130 Use this to infer values of `org-odt-styles-dir' and
131 `org-odt-schema-dir'.")
133 (defconst org-odt-special-string-regexps
134 '(("\\\\-" . "&#x00ad;\\1") ; shy
135 ("---\\([^-]\\)" . "&#x2014;\\1") ; mdash
136 ("--\\([^-]\\)" . "&#x2013;\\1") ; ndash
137 ("\\.\\.\\." . "&#x2026;")) ; hellip
138 "Regular expressions for special string conversion.")
140 (defconst org-odt-schema-dir-list
141 (list
142 (and org-odt-data-dir
143 (expand-file-name "./schema/" org-odt-data-dir)) ; bail out
144 (eval-when-compile
145 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
146 (expand-file-name "./schema/" org-odt-data-dir))))
147 "List of directories to search for OpenDocument schema files.
148 Use this list to set the default value of
149 `org-odt-schema-dir'. The entries in this list are
150 populated heuristically based on the values of `org-odt-lib-dir'
151 and `org-odt-data-dir'.")
153 (defconst org-odt-styles-dir-list
154 (list
155 (and org-odt-data-dir
156 (expand-file-name "./styles/" org-odt-data-dir)) ; bail out
157 (eval-when-compile
158 (and (boundp 'org-odt-data-dir) org-odt-data-dir ; see make install
159 (expand-file-name "./styles/" org-odt-data-dir)))
160 (expand-file-name "../../etc/styles/" org-odt-lib-dir) ; git
161 (expand-file-name "./etc/styles/" org-odt-lib-dir) ; elpa
162 (expand-file-name "./org/" data-directory) ; system
164 "List of directories to search for OpenDocument styles files.
165 See `org-odt-styles-dir'. The entries in this list are populated
166 heuristically based on the values of `org-odt-lib-dir' and
167 `org-odt-data-dir'.")
169 (defconst org-odt-styles-dir
170 (let* ((styles-dir
171 (catch 'styles-dir
172 (message "Debug (ox-odt): Searching for OpenDocument styles files...")
173 (mapc (lambda (styles-dir)
174 (when styles-dir
175 (message "Debug (ox-odt): Trying %s..." styles-dir)
176 (when (and (file-readable-p
177 (expand-file-name
178 "OrgOdtContentTemplate.xml" styles-dir))
179 (file-readable-p
180 (expand-file-name
181 "OrgOdtStyles.xml" styles-dir)))
182 (message "Debug (ox-odt): Using styles under %s"
183 styles-dir)
184 (throw 'styles-dir styles-dir))))
185 org-odt-styles-dir-list)
186 nil)))
187 (unless styles-dir
188 (error "Error (ox-odt): Cannot find factory styles files, aborting"))
189 styles-dir)
190 "Directory that holds auxiliary XML files used by the ODT exporter.
192 This directory contains the following XML files -
193 \"OrgOdtStyles.xml\" and \"OrgOdtContentTemplate.xml\". These
194 XML files are used as the default values of
195 `org-odt-styles-file' and
196 `org-odt-content-template-file'.
198 The default value of this variable varies depending on the
199 version of org in use and is initialized from
200 `org-odt-styles-dir-list'. Note that the user could be using org
201 from one of: org's own private git repository, GNU ELPA tar or
202 standard Emacs.")
204 (defconst org-odt-bookmark-prefix "OrgXref.")
206 (defconst org-odt-manifest-file-entry-tag
207 "\n<manifest:file-entry manifest:media-type=\"%s\" manifest:full-path=\"%s\"%s/>")
209 (defconst org-odt-file-extensions
210 '(("odt" . "OpenDocument Text")
211 ("ott" . "OpenDocument Text Template")
212 ("odm" . "OpenDocument Master Document")
213 ("ods" . "OpenDocument Spreadsheet")
214 ("ots" . "OpenDocument Spreadsheet Template")
215 ("odg" . "OpenDocument Drawing (Graphics)")
216 ("otg" . "OpenDocument Drawing Template")
217 ("odp" . "OpenDocument Presentation")
218 ("otp" . "OpenDocument Presentation Template")
219 ("odi" . "OpenDocument Image")
220 ("odf" . "OpenDocument Formula")
221 ("odc" . "OpenDocument Chart")))
223 (defconst org-odt-table-style-format
225 <style:style style:name=\"%s\" style:family=\"table\">
226 <style:table-properties style:rel-width=\"%d%%\" fo:margin-top=\"0cm\" fo:margin-bottom=\"0.20cm\" table:align=\"center\"/>
227 </style:style>
229 "Template for auto-generated Table styles.")
231 (defvar org-odt-automatic-styles '()
232 "Registry of automatic styles for various OBJECT-TYPEs.
233 The variable has the following form:
234 \(\(OBJECT-TYPE-A
235 \(\(OBJECT-NAME-A.1 OBJECT-PROPS-A.1\)
236 \(OBJECT-NAME-A.2 OBJECT-PROPS-A.2\) ...\)\)
237 \(OBJECT-TYPE-B
238 \(\(OBJECT-NAME-B.1 OBJECT-PROPS-B.1\)
239 \(OBJECT-NAME-B.2 OBJECT-PROPS-B.2\) ...\)\)
240 ...\).
242 OBJECT-TYPEs could be \"Section\", \"Table\", \"Figure\" etc.
243 OBJECT-PROPS is (typically) a plist created by passing
244 \"#+ATTR_ODT: \" option to `org-odt-parse-block-attributes'.
246 Use `org-odt-add-automatic-style' to add update this variable.'")
248 (defvar org-odt-object-counters nil
249 "Running counters for various OBJECT-TYPEs.
250 Use this to generate automatic names and style-names. See
251 `org-odt-add-automatic-style'.")
253 (defvar org-odt-src-block-paragraph-format
254 "<style:style style:name=\"OrgSrcBlock\" style:family=\"paragraph\" style:parent-style-name=\"Preformatted_20_Text\">
255 <style:paragraph-properties fo:background-color=\"%s\" fo:padding=\"0.049cm\" fo:border=\"0.51pt solid #000000\" style:shadow=\"none\">
256 <style:background-image/>
257 </style:paragraph-properties>
258 <style:text-properties fo:color=\"%s\"/>
259 </style:style>"
260 "Custom paragraph style for colorized source and example blocks.
261 This style is much the same as that of \"OrgFixedWidthBlock\"
262 except that the foreground and background colors are set
263 according to the default face identified by the `htmlfontify'.")
265 (defvar hfy-optimisations)
266 (defvar org-odt-embedded-formulas-count 0)
267 (defvar org-odt-embedded-images-count 0)
268 (defvar org-odt-image-size-probe-method
269 (append (and (executable-find "identify") '(imagemagick)) ; See Bug#10675
270 '(emacs fixed))
271 "Ordered list of methods for determining image sizes.")
273 (defvar org-odt-default-image-sizes-alist
274 '(("as-char" . (5 . 0.4))
275 ("paragraph" . (5 . 5)))
276 "Hardcoded image dimensions one for each of the anchor
277 methods.")
279 ;; A4 page size is 21.0 by 29.7 cms
280 ;; The default page settings has 2cm margin on each of the sides. So
281 ;; the effective text area is 17.0 by 25.7 cm
282 (defvar org-odt-max-image-size '(17.0 . 20.0)
283 "Limiting dimensions for an embedded image.")
285 (defconst org-odt-label-styles
286 '(("math-formula" "%c" "text" "(%n)")
287 ("math-label" "(%n)" "text" "(%n)")
288 ("category-and-value" "%e %n: %c" "category-and-value" "%e %n")
289 ("value" "%e %n: %c" "value" "%n"))
290 "Specify how labels are applied and referenced.
291 This is an alist where each element is of the
292 form (LABEL-STYLE-NAME LABEL-ATTACH-FMT LABEL-REF-MODE
293 LABEL-REF-FMT).
295 LABEL-ATTACH-FMT controls how labels and captions are attached to
296 an entity. It may contain following specifiers - %e, %n and %c.
297 %e is replaced with the CATEGORY-NAME. %n is replaced with
298 \"<text:sequence ...> SEQNO </text:sequence>\". %c is replaced
299 with CAPTION. See `org-odt-format-label-definition'.
301 LABEL-REF-MODE and LABEL-REF-FMT controls how label references
302 are generated. The following XML is generated for a label
303 reference - \"<text:sequence-ref
304 text:reference-format=\"LABEL-REF-MODE\" ...> LABEL-REF-FMT
305 </text:sequence-ref>\". LABEL-REF-FMT may contain following
306 specifiers - %e and %n. %e is replaced with the CATEGORY-NAME.
307 %n is replaced with SEQNO. See
308 `org-odt-format-label-reference'.")
310 (defvar org-odt-category-map-alist
311 '(("__Table__" "Table" "value" "Table" org-odt--enumerable-p)
312 ("__Figure__" "Illustration" "value" "Figure" org-odt--enumerable-image-p)
313 ("__MathFormula__" "Text" "math-formula" "Equation" org-odt--enumerable-formula-p)
314 ("__DvipngImage__" "Equation" "value" "Equation" org-odt--enumerable-latex-image-p)
315 ("__Listing__" "Listing" "value" "Listing" org-odt--enumerable-p)
316 ;; ("__Table__" "Table" "category-and-value")
317 ;; ("__Figure__" "Figure" "category-and-value")
318 ;; ("__DvipngImage__" "Equation" "category-and-value")
320 "Map a CATEGORY-HANDLE to OD-VARIABLE and LABEL-STYLE.
321 This is a list where each entry is of the form \\(CATEGORY-HANDLE
322 OD-VARIABLE LABEL-STYLE CATEGORY-NAME ENUMERATOR-PREDICATE\\).
324 CATEGORY_HANDLE identifies the captionable entity in question.
326 OD-VARIABLE is the OpenDocument sequence counter associated with
327 the entity. These counters are declared within
328 \"<text:sequence-decls>...</text:sequence-decls>\" block of
329 `org-odt-content-template-file'.
331 LABEL-STYLE is a key into `org-odt-label-styles' and specifies
332 how a given entity should be captioned and referenced.
334 CATEGORY-NAME is used for qualifying captions on export. You can
335 modify the CATEGORY-NAME used in the exported document by
336 modifying `org-export-dictionary'. For example, an embedded
337 image in an English document is captioned as \"Figure 1: Orgmode
338 Logo\", by default. If you want the image to be captioned as
339 \"Illustration 1: Orgmode Logo\" instead, install an entry in
340 `org-export-dictionary' which translates \"Figure\" to
341 \"Illustration\" when the language is \"en\" and encoding is
342 `:utf-8'.
344 ENUMERATOR-PREDICATE is used for assigning a sequence number to
345 the entity. See `org-odt--enumerate'.")
347 (defvar org-odt-manifest-file-entries nil)
348 (defvar hfy-user-sheet-assoc)
350 (defvar org-odt-zip-dir nil
351 "Temporary work directory for OpenDocument exporter.")
355 ;;; User Configuration Variables
357 (defgroup org-export-odt nil
358 "Options for exporting Org mode files to ODT."
359 :tag "Org Export ODT"
360 :group 'org-export)
363 ;;;; Debugging
365 (defcustom org-odt-prettify-xml nil
366 "Specify whether or not the xml output should be prettified.
367 When this option is turned on, `indent-region' is run on all
368 component xml buffers before they are saved. Turn this off for
369 regular use. Turn this on if you need to examine the xml
370 visually."
371 :group 'org-export-odt
372 :version "24.1"
373 :type 'boolean)
376 ;;;; Document schema
378 (defcustom org-odt-schema-dir
379 (let* ((schema-dir
380 (catch 'schema-dir
381 (message "Debug (ox-odt): Searching for OpenDocument schema files...")
382 (mapc
383 (lambda (schema-dir)
384 (when schema-dir
385 (message "Debug (ox-odt): Trying %s..." schema-dir)
386 (when (and (file-expand-wildcards
387 (expand-file-name "od-manifest-schema*.rnc"
388 schema-dir))
389 (file-expand-wildcards
390 (expand-file-name "od-schema*.rnc"
391 schema-dir))
392 (file-readable-p
393 (expand-file-name "schemas.xml" schema-dir)))
394 (message "Debug (ox-odt): Using schema files under %s"
395 schema-dir)
396 (throw 'schema-dir schema-dir))))
397 org-odt-schema-dir-list)
398 (message "Debug (ox-odt): No OpenDocument schema files installed")
399 nil)))
400 schema-dir)
401 "Directory that contains OpenDocument schema files.
403 This directory contains:
404 1. rnc files for OpenDocument schema
405 2. a \"schemas.xml\" file that specifies locating rules needed
406 for auto validation of OpenDocument XML files.
408 Use the customize interface to set this variable. This ensures
409 that `rng-schema-locating-files' is updated and auto-validation
410 of OpenDocument XML takes place based on the value
411 `rng-nxml-auto-validate-flag'.
413 The default value of this variable varies depending on the
414 version of org in use and is initialized from
415 `org-odt-schema-dir-list'. The OASIS schema files are available
416 only in the org's private git repository. It is *not* bundled
417 with GNU ELPA tar or standard Emacs distribution."
418 :type '(choice
419 (const :tag "Not set" nil)
420 (directory :tag "Schema directory"))
421 :group 'org-export-odt
422 :version "24.1"
423 :set
424 (lambda (var value)
425 "Set `org-odt-schema-dir'.
426 Also add it to `rng-schema-locating-files'."
427 (let ((schema-dir value))
428 (set var
429 (if (and
430 (file-expand-wildcards
431 (expand-file-name "od-manifest-schema*.rnc" schema-dir))
432 (file-expand-wildcards
433 (expand-file-name "od-schema*.rnc" schema-dir))
434 (file-readable-p
435 (expand-file-name "schemas.xml" schema-dir)))
436 schema-dir
437 (when value
438 (message "Error (ox-odt): %s has no OpenDocument schema files"
439 value))
440 nil)))
441 (when org-odt-schema-dir
442 (eval-after-load 'rng-loc
443 '(add-to-list 'rng-schema-locating-files
444 (expand-file-name "schemas.xml"
445 org-odt-schema-dir))))))
448 ;;;; Document styles
450 (defcustom org-odt-content-template-file nil
451 "Template file for \"content.xml\".
452 The exporter embeds the exported content just before
453 \"</office:text>\" element.
455 If unspecified, the file named \"OrgOdtContentTemplate.xml\"
456 under `org-odt-styles-dir' is used."
457 :type 'file
458 :group 'org-export-odt
459 :version "24.1")
461 (defcustom org-odt-styles-file nil
462 "Default styles file for use with ODT export.
463 Valid values are one of:
464 1. nil
465 2. path to a styles.xml file
466 3. path to a *.odt or a *.ott file
467 4. list of the form (ODT-OR-OTT-FILE (FILE-MEMBER-1 FILE-MEMBER-2
468 ...))
470 In case of option 1, an in-built styles.xml is used. See
471 `org-odt-styles-dir' for more information.
473 In case of option 3, the specified file is unzipped and the
474 styles.xml embedded therein is used.
476 In case of option 4, the specified ODT-OR-OTT-FILE is unzipped
477 and FILE-MEMBER-1, FILE-MEMBER-2 etc are copied in to the
478 generated odt file. Use relative path for specifying the
479 FILE-MEMBERS. styles.xml must be specified as one of the
480 FILE-MEMBERS.
482 Use options 1, 2 or 3 only if styles.xml alone suffices for
483 achieving the desired formatting. Use option 4, if the styles.xml
484 references additional files like header and footer images for
485 achieving the desired formatting.
487 Use \"#+ODT_STYLES_FILE: ...\" directive to set this variable on
488 a per-file basis. For example,
490 #+ODT_STYLES_FILE: \"/path/to/styles.xml\" or
491 #+ODT_STYLES_FILE: (\"/path/to/file.ott\" (\"styles.xml\" \"image/hdr.png\"))."
492 :group 'org-export-odt
493 :version "24.1"
494 :type
495 '(choice
496 (const :tag "Factory settings" nil)
497 (file :must-match t :tag "styles.xml")
498 (file :must-match t :tag "ODT or OTT file")
499 (list :tag "ODT or OTT file + Members"
500 (file :must-match t :tag "ODF Text or Text Template file")
501 (cons :tag "Members"
502 (file :tag " Member" "styles.xml")
503 (repeat (file :tag "Member"))))))
505 (defcustom org-odt-display-outline-level 2
506 "Outline levels considered for enumerating captioned entities."
507 :group 'org-export-odt
508 :version "24.2"
509 :type 'integer)
511 ;;;; Document conversion
513 (defcustom org-odt-convert-processes
514 '(("LibreOffice"
515 "soffice --headless --convert-to %f%x --outdir %d %i")
516 ("unoconv"
517 "unoconv -f %f -o %d %i"))
518 "Specify a list of document converters and their usage.
519 The converters in this list are offered as choices while
520 customizing `org-odt-convert-process'.
522 This variable is a list where each element is of the
523 form (CONVERTER-NAME CONVERTER-CMD). CONVERTER-NAME is the name
524 of the converter. CONVERTER-CMD is the shell command for the
525 converter and can contain format specifiers. These format
526 specifiers are interpreted as below:
528 %i input file name in full
529 %I input file name as a URL
530 %f format of the output file
531 %o output file name in full
532 %O output file name as a URL
533 %d output dir in full
534 %D output dir as a URL.
535 %x extra options as set in `org-odt-convert-capabilities'."
536 :group 'org-export-odt
537 :version "24.1"
538 :type
539 '(choice
540 (const :tag "None" nil)
541 (alist :tag "Converters"
542 :key-type (string :tag "Converter Name")
543 :value-type (group (string :tag "Command line")))))
545 (defcustom org-odt-convert-process "LibreOffice"
546 "Use this converter to convert from \"odt\" format to other formats.
547 During customization, the list of converter names are populated
548 from `org-odt-convert-processes'."
549 :group 'org-export-odt
550 :version "24.1"
551 :type '(choice :convert-widget
552 (lambda (w)
553 (apply 'widget-convert (widget-type w)
554 (eval (car (widget-get w :args)))))
555 `((const :tag "None" nil)
556 ,@(mapcar (lambda (c)
557 `(const :tag ,(car c) ,(car c)))
558 org-odt-convert-processes))))
560 (defcustom org-odt-convert-capabilities
561 '(("Text"
562 ("odt" "ott" "doc" "rtf" "docx")
563 (("pdf" "pdf") ("odt" "odt") ("rtf" "rtf") ("ott" "ott")
564 ("doc" "doc" ":\"MS Word 97\"") ("docx" "docx") ("html" "html")))
565 ("Web"
566 ("html")
567 (("pdf" "pdf") ("odt" "odt") ("html" "html")))
568 ("Spreadsheet"
569 ("ods" "ots" "xls" "csv" "xlsx")
570 (("pdf" "pdf") ("ots" "ots") ("html" "html") ("csv" "csv") ("ods" "ods")
571 ("xls" "xls") ("xlsx" "xlsx")))
572 ("Presentation"
573 ("odp" "otp" "ppt" "pptx")
574 (("pdf" "pdf") ("swf" "swf") ("odp" "odp") ("otp" "otp") ("ppt" "ppt")
575 ("pptx" "pptx") ("odg" "odg"))))
576 "Specify input and output formats of `org-odt-convert-process'.
577 More correctly, specify the set of input and output formats that
578 the user is actually interested in.
580 This variable is an alist where each element is of the
581 form (DOCUMENT-CLASS INPUT-FMT-LIST OUTPUT-FMT-ALIST).
582 INPUT-FMT-LIST is a list of INPUT-FMTs. OUTPUT-FMT-ALIST is an
583 alist where each element is of the form (OUTPUT-FMT
584 OUTPUT-FILE-EXTENSION EXTRA-OPTIONS).
586 The variable is interpreted as follows:
587 `org-odt-convert-process' can take any document that is in
588 INPUT-FMT-LIST and produce any document that is in the
589 OUTPUT-FMT-LIST. A document converted to OUTPUT-FMT will have
590 OUTPUT-FILE-EXTENSION as the file name extension. OUTPUT-FMT
591 serves dual purposes:
592 - It is used for populating completion candidates during
593 `org-odt-convert' commands.
594 - It is used as the value of \"%f\" specifier in
595 `org-odt-convert-process'.
597 EXTRA-OPTIONS is used as the value of \"%x\" specifier in
598 `org-odt-convert-process'.
600 DOCUMENT-CLASS is used to group a set of file formats in
601 INPUT-FMT-LIST in to a single class.
603 Note that this variable inherently captures how LibreOffice based
604 converters work. LibreOffice maps documents of various formats
605 to classes like Text, Web, Spreadsheet, Presentation etc and
606 allow document of a given class (irrespective of it's source
607 format) to be converted to any of the export formats associated
608 with that class.
610 See default setting of this variable for an typical
611 configuration."
612 :group 'org-export-odt
613 :version "24.1"
614 :type
615 '(choice
616 (const :tag "None" nil)
617 (alist :tag "Capabilities"
618 :key-type (string :tag "Document Class")
619 :value-type
620 (group (repeat :tag "Input formats" (string :tag "Input format"))
621 (alist :tag "Output formats"
622 :key-type (string :tag "Output format")
623 :value-type
624 (group (string :tag "Output file extension")
625 (choice
626 (const :tag "None" nil)
627 (string :tag "Extra options"))))))))
629 (defcustom org-odt-preferred-output-format nil
630 "Automatically post-process to this format after exporting to \"odt\".
631 Command `org-odt-export-to-odt' exports first to \"odt\" format
632 and then uses `org-odt-convert-process' to convert the
633 resulting document to this format. During customization of this
634 variable, the list of valid values are populated based on
635 `org-odt-convert-capabilities'.
637 You can set this option on per-file basis using file local
638 values. See Info node `(emacs) File Variables'."
639 :group 'org-export-odt
640 :version "24.1"
641 :type '(choice :convert-widget
642 (lambda (w)
643 (apply 'widget-convert (widget-type w)
644 (eval (car (widget-get w :args)))))
645 `((const :tag "None" nil)
646 ,@(mapcar (lambda (c)
647 `(const :tag ,c ,c))
648 (org-odt-reachable-formats "odt")))))
649 ;;;###autoload
650 (put 'org-odt-preferred-output-format 'safe-local-variable 'stringp)
653 ;;;; Drawers
655 (defcustom org-odt-format-drawer-function nil
656 "Function called to format a drawer in ODT code.
658 The function must accept two parameters:
659 NAME the drawer name, like \"LOGBOOK\"
660 CONTENTS the contents of the drawer.
662 The function should return the string to be exported.
664 For example, the variable could be set to the following function
665 in order to mimic default behaviour:
667 \(defun org-odt-format-drawer-default \(name contents\)
668 \"Format a drawer element for ODT export.\"
669 contents\)"
670 :group 'org-export-odt
671 :version "24.4"
672 :package-version '(Org . "8.0")
673 :type 'function)
676 ;;;; Headline
678 (defcustom org-odt-format-headline-function nil
679 "Function to format headline text.
681 This function will be called with 5 arguments:
682 TODO the todo keyword \(string or nil\).
683 TODO-TYPE the type of todo \(symbol: `todo', `done', nil\)
684 PRIORITY the priority of the headline \(integer or nil\)
685 TEXT the main headline text \(string\).
686 TAGS the tags string, separated with colons \(string or nil\).
688 The function result will be used as headline text."
689 :group 'org-export-odt
690 :version "24.4"
691 :package-version '(Org . "8.0")
692 :type 'function)
695 ;;;; Inlinetasks
697 (defcustom org-odt-format-inlinetask-function nil
698 "Function called to format an inlinetask in ODT code.
700 The function must accept six parameters:
701 TODO the todo keyword, as a string
702 TODO-TYPE the todo type, a symbol among `todo', `done' and nil.
703 PRIORITY the inlinetask priority, as a string
704 NAME the inlinetask name, as a string.
705 TAGS the inlinetask tags, as a string.
706 CONTENTS the contents of the inlinetask, as a string.
708 The function should return the string to be exported."
709 :group 'org-export-odt
710 :version "24.4"
711 :package-version '(Org . "8.0")
712 :type 'function)
715 ;;;; LaTeX
717 (defcustom org-odt-with-latex org-export-with-latex
718 "Non-nil means process LaTeX math snippets.
720 When set, the exporter will process LaTeX environments and
721 fragments.
723 This option can also be set with the +OPTIONS line,
724 e.g. \"tex:mathjax\". Allowed values are:
726 nil Ignore math snippets.
727 `verbatim' Keep everything in verbatim
728 `dvipng' Process the LaTeX fragments to images. This will also
729 include processing of non-math environments.
730 `imagemagick' Convert the LaTeX fragments to pdf files and use
731 imagemagick to convert pdf files to png files.
732 `mathjax' Do MathJax preprocessing and arrange for MathJax.js to
733 be loaded.
734 t Synonym for `mathjax'."
735 :group 'org-export-odt
736 :version "24.4"
737 :package-version '(Org . "8.0")
738 :type '(choice
739 (const :tag "Do not process math in any way" nil)
740 (const :tag "Use dvipng to make images" dvipng)
741 (const :tag "Use imagemagick to make images" imagemagick)
742 (const :tag "Use MathJax to display math" mathjax)
743 (const :tag "Leave math verbatim" verbatim)))
746 ;;;; Links
748 (defcustom org-odt-inline-formula-rules
749 '(("file" . "\\.\\(mathml\\|mml\\|odf\\)\\'"))
750 "Rules characterizing formula files that can be inlined into ODT.
752 A rule consists in an association whose key is the type of link
753 to consider, and value is a regexp that will be matched against
754 link's path."
755 :group 'org-export-odt
756 :type '(alist :key-type (string :tag "Type")
757 :value-type (regexp :tag "Path")))
759 (defcustom org-odt-inline-image-rules
760 '(("file" . "\\.\\(jpeg\\|jpg\\|png\\|gif\\)\\'"))
761 "Rules characterizing image files that can be inlined into ODT.
763 A rule consists in an association whose key is the type of link
764 to consider, and value is a regexp that will be matched against
765 link's path."
766 :group 'org-export-odt
767 :type '(alist :key-type (string :tag "Type")
768 :value-type (regexp :tag "Path")))
770 (defcustom org-odt-pixels-per-inch display-pixels-per-inch
771 "Scaling factor for converting images pixels to inches.
772 Use this for sizing of embedded images. See Info node `(org)
773 Images in ODT export' for more information."
774 :type 'float
775 :group 'org-export-odt
776 :version "24.1")
779 ;;;; Src Block
781 (defcustom org-odt-create-custom-styles-for-srcblocks t
782 "Whether custom styles for colorized source blocks be automatically created.
783 When this option is turned on, the exporter creates custom styles
784 for source blocks based on the advice of `htmlfontify'. Creation
785 of custom styles happen as part of `org-odt-hfy-face-to-css'.
787 When this option is turned off exporter does not create such
788 styles.
790 Use the latter option if you do not want the custom styles to be
791 based on your current display settings. It is necessary that the
792 styles.xml already contains needed styles for colorizing to work.
794 This variable is effective only if
795 `org-odt-fontify-srcblocks' is turned on."
796 :group 'org-export-odt
797 :version "24.1"
798 :type 'boolean)
800 (defcustom org-odt-fontify-srcblocks t
801 "Specify whether or not source blocks need to be fontified.
802 Turn this option on if you want to colorize the source code
803 blocks in the exported file. For colorization to work, you need
804 to make available an enhanced version of `htmlfontify' library."
805 :type 'boolean
806 :group 'org-export-odt
807 :version "24.1")
810 ;;;; Table
812 (defcustom org-odt-table-styles
813 '(("OrgEquation" "OrgEquation"
814 ((use-first-column-styles . t)
815 (use-last-column-styles . t)))
816 ("TableWithHeaderRowAndColumn" "Custom"
817 ((use-first-row-styles . t)
818 (use-first-column-styles . t)))
819 ("TableWithFirstRowandLastRow" "Custom"
820 ((use-first-row-styles . t)
821 (use-last-row-styles . t)))
822 ("GriddedTable" "Custom" nil))
823 "Specify how Table Styles should be derived from a Table Template.
824 This is a list where each element is of the
825 form (TABLE-STYLE-NAME TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS).
827 TABLE-STYLE-NAME is the style associated with the table through
828 \"#+ATTR_ODT: :style TABLE-STYLE-NAME\" line.
830 TABLE-TEMPLATE-NAME is a set of - upto 9 - automatic
831 TABLE-CELL-STYLE-NAMEs and PARAGRAPH-STYLE-NAMEs (as defined
832 below) that is included in
833 `org-odt-content-template-file'.
835 TABLE-CELL-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
836 \"TableCell\"
837 PARAGRAPH-STYLE-NAME := TABLE-TEMPLATE-NAME + TABLE-CELL-TYPE +
838 \"TableParagraph\"
839 TABLE-CELL-TYPE := \"FirstRow\" | \"LastColumn\" |
840 \"FirstRow\" | \"LastRow\" |
841 \"EvenRow\" | \"OddRow\" |
842 \"EvenColumn\" | \"OddColumn\" | \"\"
843 where \"+\" above denotes string concatenation.
845 TABLE-CELL-OPTIONS is an alist where each element is of the
846 form (TABLE-CELL-STYLE-SELECTOR . ON-OR-OFF).
847 TABLE-CELL-STYLE-SELECTOR := `use-first-row-styles' |
848 `use-last-row-styles' |
849 `use-first-column-styles' |
850 `use-last-column-styles' |
851 `use-banding-rows-styles' |
852 `use-banding-columns-styles' |
853 `use-first-row-styles'
854 ON-OR-OFF := `t' | `nil'
856 For example, with the following configuration
858 \(setq org-odt-table-styles
859 '\(\(\"TableWithHeaderRowsAndColumns\" \"Custom\"
860 \(\(use-first-row-styles . t\)
861 \(use-first-column-styles . t\)\)\)
862 \(\"TableWithHeaderColumns\" \"Custom\"
863 \(\(use-first-column-styles . t\)\)\)\)\)
865 1. A table associated with \"TableWithHeaderRowsAndColumns\"
866 style will use the following table-cell styles -
867 \"CustomFirstRowTableCell\", \"CustomFirstColumnTableCell\",
868 \"CustomTableCell\" and the following paragraph styles
869 \"CustomFirstRowTableParagraph\",
870 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
871 as appropriate.
873 2. A table associated with \"TableWithHeaderColumns\" style will
874 use the following table-cell styles -
875 \"CustomFirstColumnTableCell\", \"CustomTableCell\" and the
876 following paragraph styles
877 \"CustomFirstColumnTableParagraph\", \"CustomTableParagraph\"
878 as appropriate..
880 Note that TABLE-TEMPLATE-NAME corresponds to the
881 \"<table:table-template>\" elements contained within
882 \"<office:styles>\". The entries (TABLE-STYLE-NAME
883 TABLE-TEMPLATE-NAME TABLE-CELL-OPTIONS) correspond to
884 \"table:template-name\" and \"table:use-first-row-styles\" etc
885 attributes of \"<table:table>\" element. Refer ODF-1.2
886 specification for more information. Also consult the
887 implementation filed under `org-odt-get-table-cell-styles'.
889 The TABLE-STYLE-NAME \"OrgEquation\" is used internally for
890 formatting of numbered display equations. Do not delete this
891 style from the list."
892 :group 'org-export-odt
893 :version "24.1"
894 :type '(choice
895 (const :tag "None" nil)
896 (repeat :tag "Table Styles"
897 (list :tag "Table Style Specification"
898 (string :tag "Table Style Name")
899 (string :tag "Table Template Name")
900 (alist :options (use-first-row-styles
901 use-last-row-styles
902 use-first-column-styles
903 use-last-column-styles
904 use-banding-rows-styles
905 use-banding-columns-styles)
906 :key-type symbol
907 :value-type (const :tag "True" t))))))
909 ;;;; Timestamps
911 (defcustom org-odt-use-date-fields nil
912 "Non-nil, if timestamps should be exported as date fields.
914 When nil, export timestamps as plain text.
916 When non-nil, map `org-time-stamp-custom-formats' to a pair of
917 OpenDocument date-styles with names \"OrgDate1\" and \"OrgDate2\"
918 respectively. A timestamp with no time component is formatted
919 with style \"OrgDate1\" while one with explicit hour and minutes
920 is formatted with style \"OrgDate2\".
922 This feature is experimental. Most (but not all) of the common
923 %-specifiers in `format-time-string' are supported.
924 Specifically, locale-dependent specifiers like \"%c\", \"%x\" are
925 formatted as canonical Org timestamps. For finer control, avoid
926 these %-specifiers.
928 Textutal specifiers like \"%b\", \"%h\", \"%B\", \"%a\", \"%A\"
929 etc., are displayed by the application in the default language
930 and country specified in `org-odt-styles-file'. Note that the
931 default styles file uses language \"en\" and country \"GB\". You
932 can localize the week day and month strings in the exported
933 document by setting the default language and country either using
934 the application UI or through a custom styles file.
936 See `org-odt--build-date-styles' for implementation details."
937 :group 'org-export-odt
938 :type 'boolean)
942 ;;; Internal functions
944 ;;;; Date
946 (defun org-odt--format-timestamp (timestamp &optional end iso-date-p)
947 (let* ((format-timestamp
948 (lambda (timestamp format &optional end utc)
949 (if timestamp
950 (org-timestamp-format timestamp format end utc)
951 (format-time-string format nil utc))))
952 (has-time-p (or (not timestamp)
953 (org-timestamp-has-time-p timestamp)))
954 (iso-date (let ((format (if has-time-p "%Y-%m-%dT%H:%M:%S"
955 "%Y-%m-%dT%H:%M:%S")))
956 (funcall format-timestamp timestamp format end))))
957 (if iso-date-p iso-date
958 (let* ((style (if has-time-p "OrgDate2" "OrgDate1"))
959 ;; LibreOffice does not care about end goes as content
960 ;; within the "<text:date>...</text:date>" field. The
961 ;; displayed date is automagically corrected to match the
962 ;; format requested by "style:data-style-name" attribute. So
963 ;; don't bother about formatting the date contents to be
964 ;; compatible with "OrgDate1" and "OrgDateTime" styles. A
965 ;; simple Org-style date should suffice.
966 (date (let* ((formats
967 (if org-display-custom-times
968 (cons (substring
969 (car org-time-stamp-custom-formats) 1 -1)
970 (substring
971 (cdr org-time-stamp-custom-formats) 1 -1))
972 '("%Y-%m-%d %a" . "%Y-%m-%d %a %H:%M")))
973 (format (if has-time-p (cdr formats) (car formats))))
974 (funcall format-timestamp timestamp format end)))
975 (repeater (let ((repeater-type (org-element-property
976 :repeater-type timestamp))
977 (repeater-value (org-element-property
978 :repeater-value timestamp))
979 (repeater-unit (org-element-property
980 :repeater-unit timestamp)))
981 (concat
982 (case repeater-type
983 (catchup "++") (restart ".+") (cumulate "+"))
984 (when repeater-value
985 (number-to-string repeater-value))
986 (case repeater-unit
987 (hour "h") (day "d") (week "w") (month "m")
988 (year "y"))))))
989 (concat
990 (format "<text:date text:date-value=\"%s\" style:data-style-name=\"%s\" text:fixed=\"true\">%s</text:date>"
991 iso-date style date)
992 (and (not (string= repeater "")) " ")
993 repeater)))))
995 ;;;; Frame
997 (defun org-odt--frame (text width height style &optional extra
998 anchor-type &rest title-and-desc)
999 (let ((frame-attrs
1000 (concat
1001 (if width (format " svg:width=\"%0.2fcm\"" width) "")
1002 (if height (format " svg:height=\"%0.2fcm\"" height) "")
1003 extra
1004 (format " text:anchor-type=\"%s\"" (or anchor-type "paragraph")))))
1005 (format
1006 "\n<draw:frame draw:style-name=\"%s\"%s>\n%s\n</draw:frame>"
1007 style frame-attrs
1008 (concat text
1009 (let ((title (car title-and-desc))
1010 (desc (cadr title-and-desc)))
1011 (concat (when title
1012 (format "<svg:title>%s</svg:title>"
1013 (org-odt--encode-plain-text title t)))
1014 (when desc
1015 (format "<svg:desc>%s</svg:desc>"
1016 (org-odt--encode-plain-text desc t)))))))))
1019 ;;;; Library wrappers
1021 (defun org-odt--zip-extract (archive members target)
1022 (when (atom members) (setq members (list members)))
1023 (mapc (lambda (member)
1024 (require 'arc-mode)
1025 (let* ((--quote-file-name
1026 ;; This is shamelessly stolen from `archive-zip-extract'.
1027 (lambda (name)
1028 (if (or (not (memq system-type '(windows-nt ms-dos)))
1029 (and (boundp 'w32-quote-process-args)
1030 (null w32-quote-process-args)))
1031 (shell-quote-argument name)
1032 name)))
1033 (target (funcall --quote-file-name target))
1034 (archive (expand-file-name archive))
1035 (archive-zip-extract
1036 (list "unzip" "-qq" "-o" "-d" target))
1037 exit-code command-output)
1038 (setq command-output
1039 (with-temp-buffer
1040 (setq exit-code (archive-zip-extract archive member))
1041 (buffer-string)))
1042 (unless (zerop exit-code)
1043 (message command-output)
1044 (error "Extraction failed"))))
1045 members))
1047 (defun org-odt--suppress-some-translators (info types)
1048 ;; See comments in `org-odt-format-label' and `org-odt-toc'.
1049 (org-combine-plists
1050 info (list
1051 ;; Override translators.
1052 :translate-alist
1053 (nconc (mapcar (lambda (type) (cons type (lambda (data contents info)
1054 contents))) types)
1055 (plist-get info :translate-alist))
1056 ;; Reset data translation cache. FIXME.
1057 ;; :exported-data nil
1061 ;;;; Target
1063 (defun org-odt--target (text id)
1064 (if (not id) text
1065 (concat
1066 (format "\n<text:bookmark-start text:name=\"OrgXref.%s\"/>" id)
1067 (format "\n<text:bookmark text:name=\"%s\"/>" id) text
1068 (format "\n<text:bookmark-end text:name=\"OrgXref.%s\"/>" id))))
1070 ;;;; Textbox
1072 (defun org-odt--textbox (text width height style &optional
1073 extra anchor-type)
1074 (org-odt--frame
1075 (format "\n<draw:text-box %s>%s\n</draw:text-box>"
1076 (concat (format " fo:min-height=\"%0.2fcm\"" (or height .2))
1077 (and (not width)
1078 (format " fo:min-width=\"%0.2fcm\"" (or width .2))))
1079 text)
1080 width nil style extra anchor-type))
1084 ;;;; Table of Contents
1086 (defun org-odt-begin-toc (index-title depth)
1087 (concat
1088 (format "
1089 <text:table-of-content text:style-name=\"OrgIndexSection\" text:protected=\"true\" text:name=\"Table of Contents\">
1090 <text:table-of-content-source text:outline-level=\"%d\">
1091 <text:index-title-template text:style-name=\"Contents_20_Heading\">%s</text:index-title-template>
1092 " depth index-title)
1094 (let ((levels (number-sequence 1 10)))
1095 (mapconcat
1096 (lambda (level)
1097 (format
1099 <text:table-of-content-entry-template text:outline-level=\"%d\" text:style-name=\"Contents_20_%d\">
1100 <text:index-entry-link-start text:style-name=\"Internet_20_link\"/>
1101 <text:index-entry-chapter/>
1102 <text:index-entry-text/>
1103 <text:index-entry-link-end/>
1104 </text:table-of-content-entry-template>
1105 " level level)) levels ""))
1107 (format "
1108 </text:table-of-content-source>
1110 <text:index-body>
1111 <text:index-title text:style-name=\"Sect1\" text:name=\"Table of Contents1_Head\">
1112 <text:p text:style-name=\"Contents_20_Heading\">%s</text:p>
1113 </text:index-title>
1114 " index-title)))
1116 (defun org-odt-end-toc ()
1117 (format "
1118 </text:index-body>
1119 </text:table-of-content>
1122 (defun* org-odt-format-toc-headline
1123 (todo todo-type priority text tags
1124 &key level section-number headline-label &allow-other-keys)
1125 (setq text
1126 (concat
1127 ;; Section number.
1128 (when section-number (concat section-number ". "))
1129 ;; Todo.
1130 (when todo
1131 (let ((style (if (member todo org-done-keywords)
1132 "OrgDone" "OrgTodo")))
1133 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1134 style todo)))
1135 (when priority
1136 (let* ((style (format "OrgPriority-%s" priority))
1137 (priority (format "[#%c]" priority)))
1138 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1139 style priority)))
1140 ;; Title.
1141 text
1142 ;; Tags.
1143 (when tags
1144 (concat
1145 (format " <text:span text:style-name=\"%s\">[%s]</text:span>"
1146 "OrgTags"
1147 (mapconcat
1148 (lambda (tag)
1149 (format
1150 "<text:span text:style-name=\"%s\">%s</text:span>"
1151 "OrgTag" tag)) tags " : "))))))
1152 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
1153 headline-label text))
1155 (defun org-odt-toc (depth info)
1156 (assert (wholenump depth))
1157 ;; When a headline is marked as a radio target, as in the example below:
1159 ;; ** <<<Some Heading>>>
1160 ;; Some text.
1162 ;; suppress generation of radio targets. i.e., Radio targets are to
1163 ;; be marked as targets within /document body/ and *not* within
1164 ;; /TOC/, as otherwise there will be duplicated anchors one in TOC
1165 ;; and one in the document body.
1167 ;; FIXME-1: Currently exported headings are memoized. `org-export.el'
1168 ;; doesn't provide a way to disable memoization. So this doesn't
1169 ;; work.
1171 ;; FIXME-2: Are there any other objects that need to be suppressed
1172 ;; within TOC?
1173 (let* ((title (org-export-translate "Table of Contents" :utf-8 info))
1174 (headlines (org-export-collect-headlines
1175 info (and (wholenump depth) depth)))
1176 (translations (nconc (mapcar
1177 (lambda (type)
1178 (cons type (lambda (data contents info)
1179 contents)))
1180 (list 'radio-target))
1181 (plist-get info :translate-alist))))
1182 (when headlines
1183 (concat
1184 (org-odt-begin-toc title depth)
1185 (mapconcat
1186 (lambda (headline)
1187 (let* ((entry (org-odt-format-headline--wrap
1188 headline translations info
1189 'org-odt-format-toc-headline))
1190 (level (org-export-get-relative-level headline info))
1191 (style (format "Contents_20_%d" level)))
1192 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1193 style entry)))
1194 headlines "\n")
1195 (org-odt-end-toc)))))
1198 ;;;; Document styles
1200 (defun org-odt-add-automatic-style (object-type &optional object-props)
1201 "Create an automatic style of type OBJECT-TYPE with param OBJECT-PROPS.
1202 OBJECT-PROPS is (typically) a plist created by passing
1203 \"#+ATTR_ODT: \" option of the object in question to
1204 `org-odt-parse-block-attributes'.
1206 Use `org-odt-object-counters' to generate an automatic
1207 OBJECT-NAME and STYLE-NAME. If OBJECT-PROPS is non-nil, add a
1208 new entry in `org-odt-automatic-styles'. Return (OBJECT-NAME
1209 . STYLE-NAME)."
1210 (assert (stringp object-type))
1211 (let* ((object (intern object-type))
1212 (seqvar object)
1213 (seqno (1+ (or (plist-get org-odt-object-counters seqvar) 0)))
1214 (object-name (format "%s%d" object-type seqno)) style-name)
1215 (setq org-odt-object-counters
1216 (plist-put org-odt-object-counters seqvar seqno))
1217 (when object-props
1218 (setq style-name (format "Org%s" object-name))
1219 (setq org-odt-automatic-styles
1220 (plist-put org-odt-automatic-styles object
1221 (append (list (list style-name object-props))
1222 (plist-get org-odt-automatic-styles object)))))
1223 (cons object-name style-name)))
1225 ;;;; Checkbox
1227 (defun org-odt--checkbox (item)
1228 "Return check-box string associated to ITEM."
1229 (let ((checkbox (org-element-property :checkbox item)))
1230 (if (not checkbox) ""
1231 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1232 "OrgCode" (case checkbox
1233 (on "[&#x2713;] ") ; CHECK MARK
1234 (off "[ ] ")
1235 (trans "[-] "))))))
1237 ;;; Template
1239 (defun org-odt--build-date-styles (fmt style)
1240 ;; In LibreOffice 3.4.6, there doesn't seem to be a convenient way
1241 ;; to modify the date fields. A date could be modified by
1242 ;; offsetting in days. That's about it. Also, date and time may
1243 ;; have to be emitted as two fields - a date field and a time field
1244 ;; - separately.
1246 ;; One can add Form Controls to date and time fields so that they
1247 ;; can be easily modified. But then, the exported document will
1248 ;; become tightly coupled with LibreOffice and may not function
1249 ;; properly with other OpenDocument applications.
1251 ;; I have a strange feeling that Date styles are a bit flaky at the
1252 ;; moment.
1254 ;; The feature is experimental.
1255 (when (and fmt style)
1256 (let* ((fmt-alist
1257 '(("%A" . "<number:day-of-week number:style=\"long\"/>")
1258 ("%B" . "<number:month number:textual=\"true\" number:style=\"long\"/>")
1259 ("%H" . "<number:hours number:style=\"long\"/>")
1260 ("%M" . "<number:minutes number:style=\"long\"/>")
1261 ("%S" . "<number:seconds number:style=\"long\"/>")
1262 ("%V" . "<number:week-of-year/>")
1263 ("%Y" . "<number:year number:style=\"long\"/>")
1264 ("%a" . "<number:day-of-week number:style=\"short\"/>")
1265 ("%b" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
1266 ("%d" . "<number:day number:style=\"long\"/>")
1267 ("%e" . "<number:day number:style=\"short\"/>")
1268 ("%h" . "<number:month number:textual=\"true\" number:style=\"short\"/>")
1269 ("%k" . "<number:hours number:style=\"short\"/>")
1270 ("%m" . "<number:month number:style=\"long\"/>")
1271 ("%p" . "<number:am-pm/>")
1272 ("%y" . "<number:year number:style=\"short\"/>")))
1273 (case-fold-search nil)
1274 (re (mapconcat 'identity (mapcar 'car fmt-alist) "\\|"))
1275 match rpl (start 0) (filler-beg 0) filler-end filler output)
1276 (mapc
1277 (lambda (pair)
1278 (setq fmt (replace-regexp-in-string (car pair) (cdr pair) fmt t t)))
1279 '(("\\(?:%[[:digit:]]*N\\)" . "") ; strip ns, us and ns
1280 ("%C" . "Y") ; replace century with year
1281 ("%D" . "%m/%d/%y")
1282 ("%G" . "Y") ; year corresponding to iso week
1283 ("%I" . "%H") ; hour on a 12-hour clock
1284 ("%R" . "%H:%M")
1285 ("%T" . "%H:%M:%S")
1286 ("%U\\|%W" . "%V") ; week no. starting on Sun./Mon.
1287 ("%Z" . "") ; time zone name
1288 ("%c" . "%Y-%M-%d %a %H:%M" ) ; locale's date and time format
1289 ("%g" . "%y")
1290 ("%X" . "%x" ) ; locale's pref. time format
1291 ("%j" . "") ; day of the year
1292 ("%l" . "%k") ; like %I blank-padded
1293 ("%s" . "") ; no. of secs since 1970-01-01 00:00:00 +0000
1294 ("%n" . "<text:line-break/>")
1295 ("%r" . "%I:%M:%S %p")
1296 ("%t" . "<text:tab/>")
1297 ("%u\\|%w" . "") ; numeric day of week - Mon (1-7), Sun(0-6)
1298 ("%x" . "%Y-%M-%d %a") ; locale's pref. time format
1299 ("%z" . "") ; time zone in numeric form
1301 (while (string-match re fmt start)
1302 (setq match (match-string 0 fmt))
1303 (setq rpl (assoc-default match fmt-alist))
1304 (setq start (match-end 0))
1305 (setq filler-end (match-beginning 0))
1306 (setq filler (substring fmt (prog1 filler-beg
1307 (setq filler-beg (match-end 0)))
1308 filler-end))
1309 (setq filler (and (not (string= filler ""))
1310 (format "<number:text>%s</number:text>"
1311 (org-odt--encode-plain-text filler))))
1312 (setq output (concat output "\n" filler "\n" rpl)))
1313 (setq filler (substring fmt filler-beg))
1314 (unless (string= filler "")
1315 (setq output (concat output
1316 (format "\n<number:text>%s</number:text>"
1317 (org-odt--encode-plain-text filler)))))
1318 (format "\n<number:date-style style:name=\"%s\" %s>%s\n</number:date-style>"
1319 style
1320 (concat " number:automatic-order=\"true\""
1321 " number:format-source=\"fixed\"")
1322 output ))))
1324 (defun org-odt-template (contents info)
1325 "Return complete document string after ODT conversion.
1326 CONTENTS is the transcoded contents string. RAW-DATA is the
1327 original parsed data. INFO is a plist holding export options."
1328 ;; Write meta file.
1329 (let ((title (org-export-data (plist-get info :title) info))
1330 (author (let ((author (plist-get info :author)))
1331 (if (not author) "" (org-export-data author info))))
1332 (email (plist-get info :email))
1333 (keywords (plist-get info :keywords))
1334 (description (plist-get info :description)))
1335 (write-region
1336 (concat
1337 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
1338 <office:document-meta
1339 xmlns:office=\"urn:oasis:names:tc:opendocument:xmlns:office:1.0\"
1340 xmlns:xlink=\"http://www.w3.org/1999/xlink\"
1341 xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
1342 xmlns:meta=\"urn:oasis:names:tc:opendocument:xmlns:meta:1.0\"
1343 xmlns:ooo=\"http://openoffice.org/2004/office\"
1344 office:version=\"1.2\">
1345 <office:meta>\n"
1346 (format "<dc:creator>%s</dc:creator>\n" author)
1347 (format "<meta:initial-creator>%s</meta:initial-creator>\n" author)
1348 ;; Date, if required.
1349 (when (plist-get info :with-date)
1350 ;; Check if DATE is specified as an Org-timestamp. If yes,
1351 ;; include it as meta information. Otherwise, just use
1352 ;; today's date.
1353 (let* ((date (let ((date (plist-get info :date)))
1354 (and (not (cdr date))
1355 (eq (org-element-type (car date)) 'timestamp)
1356 (car date)))))
1357 (let ((iso-date (org-odt--format-timestamp date nil 'iso-date)))
1358 (concat
1359 (format "<dc:date>%s</dc:date>\n" iso-date)
1360 (format "<meta:creation-date>%s</meta:creation-date>\n"
1361 iso-date)))))
1362 (format "<meta:generator>%s</meta:generator>\n"
1363 (let ((creator-info (plist-get info :with-creator)))
1364 (if (or (not creator-info) (eq creator-info 'comment)) ""
1365 (plist-get info :creator))))
1366 (format "<meta:keyword>%s</meta:keyword>\n" keywords)
1367 (format "<dc:subject>%s</dc:subject>\n" description)
1368 (format "<dc:title>%s</dc:title>\n" title)
1369 "\n"
1370 " </office:meta>\n" "</office:document-meta>")
1371 nil (concat org-odt-zip-dir "meta.xml"))
1372 ;; Add meta.xml in to manifest.
1373 (org-odt-create-manifest-file-entry "text/xml" "meta.xml"))
1375 ;; Update styles file.
1376 ;; Copy styles.xml. Also dump htmlfontify styles, if there is any.
1377 ;; Write styles file.
1378 (let* ((styles-file (plist-get info :odt-styles-file))
1379 (styles-file (and styles-file (read (org-trim styles-file))))
1380 ;; Non-availability of styles.xml is not a critical
1381 ;; error. For now, throw an error.
1382 (styles-file (or styles-file
1383 org-odt-styles-file
1384 (expand-file-name "OrgOdtStyles.xml"
1385 org-odt-styles-dir)
1386 (error "org-odt: Missing styles file?"))))
1387 (cond
1388 ((listp styles-file)
1389 (let ((archive (nth 0 styles-file))
1390 (members (nth 1 styles-file)))
1391 (org-odt--zip-extract archive members org-odt-zip-dir)
1392 (mapc
1393 (lambda (member)
1394 (when (org-file-image-p member)
1395 (let* ((image-type (file-name-extension member))
1396 (media-type (format "image/%s" image-type)))
1397 (org-odt-create-manifest-file-entry media-type member))))
1398 members)))
1399 ((and (stringp styles-file) (file-exists-p styles-file))
1400 (let ((styles-file-type (file-name-extension styles-file)))
1401 (cond
1402 ((string= styles-file-type "xml")
1403 (copy-file styles-file (concat org-odt-zip-dir "styles.xml") t))
1404 ((member styles-file-type '("odt" "ott"))
1405 (org-odt--zip-extract styles-file "styles.xml" org-odt-zip-dir)))))
1407 (error (format "Invalid specification of styles.xml file: %S"
1408 org-odt-styles-file))))
1410 ;; create a manifest entry for styles.xml
1411 (org-odt-create-manifest-file-entry "text/xml" "styles.xml")
1413 ;; FIXME: Who is opening an empty styles.xml before this point?
1414 (with-current-buffer
1415 (find-file-noselect (concat org-odt-zip-dir "styles.xml") t)
1416 (revert-buffer t t)
1418 ;; Write custom styles for source blocks
1419 ;; Save STYLES used for colorizing of source blocks.
1420 ;; Update styles.xml with styles that were collected as part of
1421 ;; `org-odt-hfy-face-to-css' callbacks.
1422 (let ((styles (mapconcat (lambda (style) (format " %s\n" (cddr style)))
1423 hfy-user-sheet-assoc "")))
1424 (when styles
1425 (goto-char (point-min))
1426 (when (re-search-forward "</office:styles>" nil t)
1427 (goto-char (match-beginning 0))
1428 (insert "\n<!-- Org Htmlfontify Styles -->\n" styles "\n"))))
1430 ;; Update styles.xml - take care of outline numbering
1432 ;; Don't make automatic backup of styles.xml file. This setting
1433 ;; prevents the backed-up styles.xml file from being zipped in to
1434 ;; odt file. This is more of a hackish fix. Better alternative
1435 ;; would be to fix the zip command so that the output odt file
1436 ;; includes only the needed files and excludes any auto-generated
1437 ;; extra files like backups and auto-saves etc etc. Note that
1438 ;; currently the zip command zips up the entire temp directory so
1439 ;; that any auto-generated files created under the hood ends up in
1440 ;; the resulting odt file.
1441 (set (make-local-variable 'backup-inhibited) t)
1443 ;; Outline numbering is retained only upto LEVEL.
1444 ;; To disable outline numbering pass a LEVEL of 0.
1446 (goto-char (point-min))
1447 (let ((regex
1448 "<text:outline-level-style\\([^>]*\\)text:level=\"\\([^\"]*\\)\"\\([^>]*\\)>")
1449 (replacement
1450 "<text:outline-level-style\\1text:level=\"\\2\" style:num-format=\"\">"))
1451 (while (re-search-forward regex nil t)
1452 (unless (let ((sec-num (plist-get info :section-numbers))
1453 (level (string-to-number (match-string 2))))
1454 (if (wholenump sec-num) (<= level sec-num) sec-num))
1455 (replace-match replacement t nil))))
1456 (save-buffer 0)))
1457 ;; Update content.xml.
1459 (let* ( ;; `org-display-custom-times' should be accessed right
1460 ;; within the context of the Org buffer. So obtain it's
1461 ;; value before moving on to temp-buffer context down below.
1462 (custom-time-fmts
1463 (if org-display-custom-times
1464 (cons (substring (car org-time-stamp-custom-formats) 1 -1)
1465 (substring (cdr org-time-stamp-custom-formats) 1 -1))
1466 '("%Y-%M-%d %a" . "%Y-%M-%d %a %H:%M"))))
1467 (with-temp-buffer
1468 (insert-file-contents
1469 (or org-odt-content-template-file
1470 (expand-file-name "OrgOdtContentTemplate.xml"
1471 org-odt-styles-dir)))
1472 ;; Write automatic styles.
1473 ;; - Position the cursor.
1474 (goto-char (point-min))
1475 (re-search-forward " </office:automatic-styles>" nil t)
1476 (goto-char (match-beginning 0))
1477 ;; - Dump automatic table styles.
1478 (loop for (style-name props) in
1479 (plist-get org-odt-automatic-styles 'Table) do
1480 (when (setq props (or (plist-get props :rel-width) 96))
1481 (insert (format org-odt-table-style-format style-name props))))
1482 ;; - Dump date-styles.
1483 (when org-odt-use-date-fields
1484 (insert (org-odt--build-date-styles (car custom-time-fmts)
1485 "OrgDate1")
1486 (org-odt--build-date-styles (cdr custom-time-fmts)
1487 "OrgDate2")))
1488 ;; Update display level.
1489 ;; - Remove existing sequence decls. Also position the cursor.
1490 (goto-char (point-min))
1491 (when (re-search-forward "<text:sequence-decls" nil t)
1492 (delete-region (match-beginning 0)
1493 (re-search-forward "</text:sequence-decls>" nil nil)))
1494 ;; Update sequence decls according to user preference.
1495 (insert
1496 (format
1497 "\n<text:sequence-decls>\n%s\n</text:sequence-decls>"
1498 (mapconcat
1499 (lambda (x)
1500 (format
1501 "<text:sequence-decl text:display-outline-level=\"%d\" text:name=\"%s\"/>"
1502 org-odt-display-outline-level (nth 1 x)))
1503 org-odt-category-map-alist "\n")))
1504 ;; Position the cursor to document body.
1505 (goto-char (point-min))
1506 (re-search-forward "</office:text>" nil nil)
1507 (goto-char (match-beginning 0))
1509 ;; Preamble - Title, Author, Date etc.
1510 (insert
1511 (let* ((title (org-export-data (plist-get info :title) info))
1512 (author (and (plist-get info :with-author)
1513 (let ((auth (plist-get info :author)))
1514 (and auth (org-export-data auth info)))))
1515 (email (plist-get info :email))
1516 ;; Switch on or off above vars based on user settings
1517 (author (and (plist-get info :with-author) (or author email)))
1518 (email (and (plist-get info :with-email) email)))
1519 (concat
1520 ;; Title.
1521 (when title
1522 (concat
1523 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1524 "OrgTitle" (format "\n<text:title>%s</text:title>" title))
1525 ;; Separator.
1526 "\n<text:p text:style-name=\"OrgTitle\"/>"))
1527 (cond
1528 ((and author (not email))
1529 ;; Author only.
1530 (concat
1531 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1532 "OrgSubtitle"
1533 (format "<text:initial-creator>%s</text:initial-creator>" author))
1534 ;; Separator.
1535 "\n<text:p text:style-name=\"OrgSubtitle\"/>"))
1536 ((and author email)
1537 ;; Author and E-mail.
1538 (concat
1539 (format
1540 "\n<text:p text:style-name=\"%s\">%s</text:p>"
1541 "OrgSubtitle"
1542 (format
1543 "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
1544 (concat "mailto:" email)
1545 (format "<text:initial-creator>%s</text:initial-creator>" author)))
1546 ;; Separator.
1547 "\n<text:p text:style-name=\"OrgSubtitle\"/>")))
1548 ;; Date, if required.
1549 (when (plist-get info :with-date)
1550 (let* ((date (plist-get info :date))
1551 ;; Check if DATE is specified as a timestamp.
1552 (timestamp (and (not (cdr date))
1553 (eq (org-element-type (car date)) 'timestamp)
1554 (car date))))
1555 (concat
1556 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1557 "OrgSubtitle"
1558 (if (and org-odt-use-date-fields timestamp)
1559 (org-odt--format-timestamp (car date))
1560 (org-export-data (plist-get info :date) info)))
1561 ;; Separator
1562 "<text:p text:style-name=\"OrgSubtitle\"/>"))))))
1563 ;; Table of Contents
1564 (let* ((with-toc (plist-get info :with-toc))
1565 (depth (and with-toc (if (wholenump with-toc)
1566 with-toc
1567 (plist-get info :headline-levels)))))
1568 (when depth (insert (or (org-odt-toc depth info) ""))))
1569 ;; Contents.
1570 (insert contents)
1571 ;; Return contents.
1572 (buffer-substring-no-properties (point-min) (point-max)))))
1576 ;;; Transcode Functions
1578 ;;;; Bold
1580 (defun org-odt-bold (bold contents info)
1581 "Transcode BOLD from Org to ODT.
1582 CONTENTS is the text with bold markup. INFO is a plist holding
1583 contextual information."
1584 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1585 "Bold" contents))
1588 ;;;; Center Block
1590 (defun org-odt-center-block (center-block contents info)
1591 "Transcode a CENTER-BLOCK element from Org to ODT.
1592 CONTENTS holds the contents of the center block. INFO is a plist
1593 holding contextual information."
1594 contents)
1597 ;;;; Clock
1599 (defun org-odt-clock (clock contents info)
1600 "Transcode a CLOCK element from Org to ODT.
1601 CONTENTS is nil. INFO is a plist used as a communication
1602 channel."
1603 (let ((timestamp (org-element-property :value clock))
1604 (duration (org-element-property :duration clock)))
1605 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1606 (if (eq (org-element-type (org-export-get-next-element clock info))
1607 'clock) "OrgClock" "OrgClockLastLine")
1608 (concat
1609 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1610 "OrgClockKeyword" org-clock-string)
1611 (org-odt-timestamp timestamp contents info)
1612 (and duration (format " (%s)" duration))))))
1615 ;;;; Code
1617 (defun org-odt-code (code contents info)
1618 "Transcode a CODE object from Org to ODT.
1619 CONTENTS is nil. INFO is a plist used as a communication
1620 channel."
1621 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1622 "OrgCode" (org-odt--encode-plain-text
1623 (org-element-property :value code))))
1626 ;;;; Comment
1628 ;; Comments are ignored.
1631 ;;;; Comment Block
1633 ;; Comment Blocks are ignored.
1636 ;;;; Drawer
1638 (defun org-odt-drawer (drawer contents info)
1639 "Transcode a DRAWER element from Org to ODT.
1640 CONTENTS holds the contents of the block. INFO is a plist
1641 holding contextual information."
1642 (let* ((name (org-element-property :drawer-name drawer))
1643 (output (if (functionp org-odt-format-drawer-function)
1644 (funcall org-odt-format-drawer-function
1645 name contents)
1646 ;; If there's no user defined function: simply
1647 ;; display contents of the drawer.
1648 contents)))
1649 output))
1652 ;;;; Dynamic Block
1654 (defun org-odt-dynamic-block (dynamic-block contents info)
1655 "Transcode a DYNAMIC-BLOCK element from Org to ODT.
1656 CONTENTS holds the contents of the block. INFO is a plist
1657 holding contextual information. See `org-export-data'."
1658 contents)
1661 ;;;; Entity
1663 (defun org-odt-entity (entity contents info)
1664 "Transcode an ENTITY object from Org to ODT.
1665 CONTENTS are the definition itself. INFO is a plist holding
1666 contextual information."
1667 (org-element-property :utf-8 entity))
1670 ;;;; Example Block
1672 (defun org-odt-example-block (example-block contents info)
1673 "Transcode a EXAMPLE-BLOCK element from Org to ODT.
1674 CONTENTS is nil. INFO is a plist holding contextual information."
1675 (org-odt-format-code example-block info))
1678 ;;;; Export Snippet
1680 (defun org-odt-export-snippet (export-snippet contents info)
1681 "Transcode a EXPORT-SNIPPET object from Org to ODT.
1682 CONTENTS is nil. INFO is a plist holding contextual information."
1683 (when (eq (org-export-snippet-backend export-snippet) 'odt)
1684 (org-element-property :value export-snippet)))
1687 ;;;; Export Block
1689 (defun org-odt-export-block (export-block contents info)
1690 "Transcode a EXPORT-BLOCK element from Org to ODT.
1691 CONTENTS is nil. INFO is a plist holding contextual information."
1692 (when (string= (org-element-property :type export-block) "ODT")
1693 (org-remove-indentation (org-element-property :value export-block))))
1696 ;;;; Fixed Width
1698 (defun org-odt-fixed-width (fixed-width contents info)
1699 "Transcode a FIXED-WIDTH element from Org to ODT.
1700 CONTENTS is nil. INFO is a plist holding contextual information."
1701 (org-odt-do-format-code (org-element-property :value fixed-width)))
1704 ;;;; Footnote Definition
1706 ;; Footnote Definitions are ignored.
1709 ;;;; Footnote Reference
1711 (defun org-odt-footnote-reference (footnote-reference contents info)
1712 "Transcode a FOOTNOTE-REFERENCE element from Org to ODT.
1713 CONTENTS is nil. INFO is a plist holding contextual information."
1714 (let ((--format-footnote-definition
1715 (function
1716 (lambda (n def)
1717 (setq n (format "%d" n))
1718 (let ((id (concat "fn" n))
1719 (note-class "footnote")
1720 (par-style "Footnote"))
1721 (format
1722 "<text:note text:id=\"%s\" text:note-class=\"%s\">%s</text:note>"
1723 id note-class
1724 (concat
1725 (format "<text:note-citation>%s</text:note-citation>" n)
1726 (format "<text:note-body>%s</text:note-body>" def)))))))
1727 (--format-footnote-reference
1728 (function
1729 (lambda (n)
1730 (setq n (format "%d" n))
1731 (let ((note-class "footnote")
1732 (ref-format "text")
1733 (ref-name (concat "fn" n)))
1734 (format
1735 "<text:span text:style-name=\"%s\">%s</text:span>"
1736 "OrgSuperscript"
1737 (format "<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:note-ref>"
1738 note-class ref-format ref-name n)))))))
1739 (concat
1740 ;; Insert separator between two footnotes in a row.
1741 (let ((prev (org-export-get-previous-element footnote-reference info)))
1742 (and (eq (org-element-type prev) 'footnote-reference)
1743 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1744 "OrgSuperscript" ",")))
1745 ;; Trancode footnote reference.
1746 (let ((n (org-export-get-footnote-number footnote-reference info)))
1747 (cond
1748 ((not (org-export-footnote-first-reference-p footnote-reference info))
1749 (funcall --format-footnote-reference n))
1750 ;; Inline definitions are secondary strings.
1751 ;; Non-inline footnotes definitions are full Org data.
1753 (let* ((raw (org-export-get-footnote-definition footnote-reference
1754 info))
1755 (def (let ((def (org-trim (org-export-data raw info))))
1756 (if (eq (org-element-type raw) 'org-data) def
1757 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1758 "Footnote" def)))))
1759 (funcall --format-footnote-definition n def))))))))
1762 ;;;; Headline
1764 (defun* org-odt-format-headline
1765 (todo todo-type priority text tags
1766 &key level section-number headline-label &allow-other-keys)
1767 (concat
1768 ;; Todo.
1769 (when todo
1770 (let ((style (if (member todo org-done-keywords) "OrgDone" "OrgTodo")))
1771 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1772 style todo)))
1773 (when priority
1774 (let* ((style (format "OrgPriority-%s" priority))
1775 (priority (format "[#%c]" priority)))
1776 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1777 style priority)))
1778 ;; Title.
1779 text
1780 ;; Tags.
1781 (when tags
1782 (concat
1783 "<text:tab/>"
1784 (format "<text:span text:style-name=\"%s\">[%s]</text:span>"
1785 "OrgTags" (mapconcat
1786 (lambda (tag)
1787 (format
1788 "<text:span text:style-name=\"%s\">%s</text:span>"
1789 "OrgTag" tag)) tags " : "))))))
1791 (defun org-odt-format-headline--wrap (headline translations info
1792 &optional format-function
1793 &rest extra-keys)
1794 "Transcode a HEADLINE element from Org to ODT.
1795 CONTENTS holds the contents of the headline. INFO is a plist
1796 holding contextual information."
1797 (setq translations (or translations (plist-get info :translate-alist)))
1798 (let* ((level (+ (org-export-get-relative-level headline info)))
1799 (headline-number (org-export-get-headline-number headline info))
1800 (section-number (and (org-export-numbered-headline-p headline info)
1801 (mapconcat 'number-to-string
1802 headline-number ".")))
1803 (todo (and (plist-get info :with-todo-keywords)
1804 (let ((todo (org-element-property :todo-keyword headline)))
1805 (and todo (org-export-data-with-translations
1806 todo translations info)))))
1807 (todo-type (and todo (org-element-property :todo-type headline)))
1808 (priority (and (plist-get info :with-priority)
1809 (org-element-property :priority headline)))
1810 (text (org-export-data-with-translations
1811 (org-element-property :title headline) translations info))
1812 (tags (and (plist-get info :with-tags)
1813 (org-export-get-tags headline info)))
1814 (headline-label (concat "sec-" (mapconcat 'number-to-string
1815 headline-number "-")))
1816 (format-function (cond
1817 ((functionp format-function) format-function)
1818 ((functionp org-odt-format-headline-function)
1819 (function*
1820 (lambda (todo todo-type priority text tags
1821 &allow-other-keys)
1822 (funcall org-odt-format-headline-function
1823 todo todo-type priority text tags))))
1824 (t 'org-odt-format-headline))))
1825 (apply format-function
1826 todo todo-type priority text tags
1827 :headline-label headline-label :level level
1828 :section-number section-number extra-keys)))
1830 (defun org-odt-headline (headline contents info)
1831 "Transcode a HEADLINE element from Org to ODT.
1832 CONTENTS holds the contents of the headline. INFO is a plist
1833 holding contextual information."
1834 ;; Case 1: This is a footnote section: ignore it.
1835 (unless (org-element-property :footnote-section-p headline)
1836 (let* ((text (org-export-data (org-element-property :title headline) info))
1837 ;; Create the headline text.
1838 (full-text (org-odt-format-headline--wrap headline nil info))
1839 ;; Get level relative to current parsed data.
1840 (level (org-export-get-relative-level headline info))
1841 ;; Get canonical label for the headline.
1842 (id (concat "sec-" (mapconcat 'number-to-string
1843 (org-export-get-headline-number
1844 headline info) "-")))
1845 ;; Get user-specified labels for the headline.
1846 (extra-ids (list (org-element-property :CUSTOM_ID headline)
1847 (org-element-property :ID headline)))
1848 ;; Extra targets.
1849 (extra-targets
1850 (mapconcat (lambda (x)
1851 (when x
1852 (let ((x (if (org-uuidgen-p x) (concat "ID-" x) x)))
1853 (org-odt--target
1854 "" (org-export-solidify-link-text x)))))
1855 extra-ids ""))
1856 ;; Title.
1857 (anchored-title (org-odt--target full-text id)))
1858 (cond
1859 ;; Case 2. This is a deep sub-tree: export it as a list item.
1860 ;; Also export as items headlines for which no section
1861 ;; format has been found.
1862 ((org-export-low-level-p headline info)
1863 ;; Build the real contents of the sub-tree.
1864 (concat
1865 (and (org-export-first-sibling-p headline info)
1866 (format "\n<text:list text:style-name=\"%s\" %s>"
1867 ;; Choose style based on list type.
1868 (if (org-export-numbered-headline-p headline info)
1869 "OrgNumberedList" "OrgBulletedList")
1870 ;; If top-level list, re-start numbering. Otherwise,
1871 ;; continue numbering.
1872 (format "text:continue-numbering=\"%s\""
1873 (let* ((parent (org-export-get-parent-headline
1874 headline)))
1875 (if (and parent
1876 (org-export-low-level-p parent info))
1877 "true" "false")))))
1878 (let ((headline-has-table-p
1879 (let ((section (assq 'section (org-element-contents headline))))
1880 (assq 'table (and section (org-element-contents section))))))
1881 (format "\n<text:list-item>\n%s\n%s"
1882 (concat
1883 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1884 "Text_20_body"
1885 (concat extra-targets anchored-title))
1886 contents)
1887 (if headline-has-table-p
1888 "</text:list-header>"
1889 "</text:list-item>")))
1890 (and (org-export-last-sibling-p headline info)
1891 "</text:list>")))
1892 ;; Case 3. Standard headline. Export it as a section.
1894 (concat
1895 (format
1896 "\n<text:h text:style-name=\"%s\" text:outline-level=\"%s\">%s</text:h>"
1897 (format "Heading_20_%s" level)
1898 level
1899 (concat extra-targets anchored-title))
1900 contents))))))
1903 ;;;; Horizontal Rule
1905 (defun org-odt-horizontal-rule (horizontal-rule contents info)
1906 "Transcode an HORIZONTAL-RULE object from Org to ODT.
1907 CONTENTS is nil. INFO is a plist holding contextual information."
1908 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1909 "Horizontal_20_Line" ""))
1912 ;;;; Inline Babel Call
1914 ;; Inline Babel Calls are ignored.
1917 ;;;; Inline Src Block
1919 (defun org-odt--find-verb-separator (s)
1920 "Return a character not used in string S.
1921 This is used to choose a separator for constructs like \\verb."
1922 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
1923 (loop for c across ll
1924 when (not (string-match (regexp-quote (char-to-string c)) s))
1925 return (char-to-string c))))
1927 (defun org-odt-inline-src-block (inline-src-block contents info)
1928 "Transcode an INLINE-SRC-BLOCK element from Org to ODT.
1929 CONTENTS holds the contents of the item. INFO is a plist holding
1930 contextual information."
1931 (let* ((org-lang (org-element-property :language inline-src-block))
1932 (code (org-element-property :value inline-src-block))
1933 (separator (org-odt--find-verb-separator code)))
1934 (error "FIXME")))
1937 ;;;; Inlinetask
1939 (defun org-odt-inlinetask (inlinetask contents info)
1940 "Transcode an INLINETASK element from Org to ODT.
1941 CONTENTS holds the contents of the block. INFO is a plist
1942 holding contextual information."
1943 (cond
1944 ;; If `org-odt-format-inlinetask-function' is provided, call it
1945 ;; with appropriate arguments.
1946 ((functionp org-odt-format-inlinetask-function)
1947 (let ((format-function
1948 (function*
1949 (lambda (todo todo-type priority text tags
1950 &key contents &allow-other-keys)
1951 (funcall org-odt-format-inlinetask-function
1952 todo todo-type priority text tags contents)))))
1953 (org-odt-format-headline--wrap
1954 inlinetask nil info format-function :contents contents)))
1955 ;; Otherwise, use a default template.
1957 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1958 "Text_20_body"
1959 (org-odt--textbox
1960 (concat
1961 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1962 "OrgInlineTaskHeading"
1963 (org-odt-format-headline--wrap inlinetask nil info))
1964 contents)
1965 nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))))
1967 ;;;; Italic
1969 (defun org-odt-italic (italic contents info)
1970 "Transcode ITALIC from Org to ODT.
1971 CONTENTS is the text with italic markup. INFO is a plist holding
1972 contextual information."
1973 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1974 "Emphasis" contents))
1977 ;;;; Item
1979 (defun org-odt-item (item contents info)
1980 "Transcode an ITEM element from Org to ODT.
1981 CONTENTS holds the contents of the item. INFO is a plist holding
1982 contextual information."
1983 (let* ((plain-list (org-export-get-parent item))
1984 (type (org-element-property :type plain-list))
1985 (counter (org-element-property :counter item))
1986 (tag (let ((tag (org-element-property :tag item)))
1987 (and tag
1988 (concat (org-odt--checkbox item)
1989 (org-export-data tag info))))))
1990 (case type
1991 ((ordered unordered descriptive-1 descriptive-2)
1992 (format "\n<text:list-item>\n%s\n%s"
1993 contents
1994 (let* ((--element-has-a-table-p
1995 (function
1996 (lambda (element info)
1997 (loop for el in (org-element-contents element)
1998 thereis (eq (org-element-type el) 'table))))))
1999 (cond
2000 ((funcall --element-has-a-table-p item info)
2001 "</text:list-header>")
2002 (t "</text:list-item>")))))
2003 (t (error "Unknown list type: %S" type)))))
2005 ;;;; Keyword
2007 (defun org-odt-keyword (keyword contents info)
2008 "Transcode a KEYWORD element from Org to ODT.
2009 CONTENTS is nil. INFO is a plist holding contextual information."
2010 (let ((key (org-element-property :key keyword))
2011 (value (org-element-property :value keyword)))
2012 (cond
2013 ((string= key "ODT") value)
2014 ((string= key "INDEX")
2015 ;; FIXME
2016 (ignore))
2017 ((string= key "TARGET") nil)
2018 ((string= key "TOC")
2019 (let ((value (downcase value)))
2020 (cond
2021 ((string-match "\\<headlines\\>" value)
2022 (let ((depth (or (and (string-match "[0-9]+" value)
2023 (string-to-number (match-string 0 value)))
2024 (plist-get info :with-toc))))
2025 (when (wholenump depth) (org-odt-toc depth info))))
2026 ((member value '("tables" "figures" "listings"))
2027 ;; FIXME
2028 (ignore))))))))
2031 ;;;; Latex Environment
2034 ;; (eval-after-load 'ox-odt '(ad-deactivate 'org-format-latex-as-mathml))
2035 ;; (defadvice org-format-latex-as-mathml ; FIXME
2036 ;; (after org-odt-protect-latex-fragment activate)
2037 ;; "Encode LaTeX fragment as XML.
2038 ;; Do this when translation to MathML fails."
2039 ;; (unless (> (length ad-return-value) 0)
2040 ;; (setq ad-return-value (org-odt--encode-plain-text (ad-get-arg 0)))))
2042 (defun org-odt-latex-environment (latex-environment contents info)
2043 "Transcode a LATEX-ENVIRONMENT element from Org to ODT.
2044 CONTENTS is nil. INFO is a plist holding contextual information."
2045 (let* ((latex-frag (org-remove-indentation
2046 (org-element-property :value latex-environment))))
2047 (org-odt-do-format-code latex-frag)))
2050 ;;;; Latex Fragment
2052 ;; (when latex-frag ; FIXME
2053 ;; (setq href (org-propertize href :title "LaTeX Fragment"
2054 ;; :description latex-frag)))
2055 ;; handle verbatim
2056 ;; provide descriptions
2058 (defun org-odt-latex-fragment (latex-fragment contents info)
2059 "Transcode a LATEX-FRAGMENT object from Org to ODT.
2060 CONTENTS is nil. INFO is a plist holding contextual information."
2061 (let* ((latex-frag (org-element-property :value latex-fragment))
2062 (processing-type (plist-get info :with-latex)))
2063 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2064 "OrgCode" (org-odt--encode-plain-text latex-frag t))))
2067 ;;;; Line Break
2069 (defun org-odt-line-break (line-break contents info)
2070 "Transcode a LINE-BREAK object from Org to ODT.
2071 CONTENTS is nil. INFO is a plist holding contextual information."
2072 "<text:line-break/>\n")
2075 ;;;; Link
2077 ;;;; Links :: Label references
2079 (defun org-odt--enumerate (element info &optional predicate n)
2080 (when predicate (assert (funcall predicate element info)))
2081 (let* ((--numbered-parent-headline-at-<=-n
2082 (function
2083 (lambda (element n info)
2084 (loop for x in (org-export-get-genealogy element)
2085 thereis (and (eq (org-element-type x) 'headline)
2086 (<= (org-export-get-relative-level x info) n)
2087 (org-export-numbered-headline-p x info)
2088 x)))))
2089 (--enumerate
2090 (function
2091 (lambda (element scope info &optional predicate)
2092 (let ((counter 0))
2093 (org-element-map (or scope (plist-get info :parse-tree))
2094 (org-element-type element)
2095 (lambda (el)
2096 (and (or (not predicate) (funcall predicate el info))
2097 (incf counter)
2098 (eq element el)
2099 counter))
2100 info 'first-match)))))
2101 (scope (funcall --numbered-parent-headline-at-<=-n
2102 element (or n org-odt-display-outline-level) info))
2103 (ordinal (funcall --enumerate element scope info predicate))
2104 (tag
2105 (concat
2106 ;; Section number.
2107 (and scope
2108 (mapconcat 'number-to-string
2109 (org-export-get-headline-number scope info) "."))
2110 ;; Separator.
2111 (and scope ".")
2112 ;; Ordinal.
2113 (number-to-string ordinal))))
2114 tag))
2116 (defun org-odt-format-label (element info op)
2117 (assert (memq (org-element-type element) '(link table src-block paragraph)))
2118 (let* ((caption-from
2119 (case (org-element-type element)
2120 (link (org-export-get-parent-element element))
2121 (t element)))
2122 ;; Get label and caption.
2123 (label (org-element-property :name caption-from))
2124 (caption (org-export-get-caption caption-from))
2125 (short-caption (org-export-get-caption caption-from t))
2126 ;; Transcode captions.
2127 (caption (and caption (org-export-data caption info)))
2128 ;; Currently short caption are sneaked in as object names.
2130 ;; The advantages are:
2132 ;; - Table Of Contents: Currently, there is no support for
2133 ;; building TOC for figures, listings and tables. See
2134 ;; `org-odt-keyword'. User instead has to rely on
2135 ;; external application for building such indices. Within
2136 ;; LibreOffice, building an "Illustration Index" or "Index
2137 ;; of Tables" will create a table with long captions (only)
2138 ;; and building a table with "Object names" will create a
2139 ;; table with short captions.
2141 ;; - Easy navigation: In LibreOffice, object names are
2142 ;; offered via the navigation bar. This way one can
2143 ;; quickly locate and jump to object of his choice in the
2144 ;; exported document.
2146 ;; The main disadvantage is that there cannot be any markups
2147 ;; within object names i.e., one cannot embolden, italicize
2148 ;; or underline text within short caption. So suppress
2149 ;; generation of <text:span >...</text:span> and other
2150 ;; markups by overriding the default translators. We
2151 ;; probably shouldn't be suppressing translators for all
2152 ;; elements in `org-element-all-objects', but for now this
2153 ;; will do.
2154 (short-caption
2155 (let ((short-caption (or short-caption caption))
2156 (translations (nconc (mapcar
2157 (lambda (type)
2158 (cons type (lambda (data contents info)
2159 contents)))
2160 org-element-all-objects)
2161 (plist-get info :translate-alist))))
2162 (when short-caption
2163 (org-export-data-with-translations short-caption
2164 translations info)))))
2165 (when (or label caption)
2166 (let* ((default-category
2167 (case (org-element-type element)
2168 (table "__Table__")
2169 (src-block "__Listing__")
2170 ((link paragraph)
2171 (cond
2172 ((org-odt--enumerable-latex-image-p element info)
2173 "__DvipngImage__")
2174 ((org-odt--enumerable-image-p element info)
2175 "__Figure__")
2176 ((org-odt--enumerable-formula-p element info)
2177 "__MathFormula__")
2178 (t (error "Don't know how to format label for link: %S"
2179 element))))
2180 (t (error "Don't know how to format label for element type: %s"
2181 (org-element-type element)))))
2182 seqno)
2183 (assert default-category)
2184 (destructuring-bind (counter label-style category predicate)
2185 (assoc-default default-category org-odt-category-map-alist)
2186 ;; Compute sequence number of the element.
2187 (setq seqno (org-odt--enumerate element info predicate))
2188 ;; Localize category string.
2189 (setq category (org-export-translate category :utf-8 info))
2190 (case op
2191 ;; Case 1: Handle Label definition.
2192 (definition
2193 ;; Assign an internal label, if user has not provided one
2194 (setq label (or label (format "%s-%s" default-category seqno)))
2195 (setq label (org-export-solidify-link-text label))
2196 (cons
2197 (concat
2198 ;; Sneak in a bookmark. The bookmark is used when the
2199 ;; labeled element is referenced with a link that
2200 ;; provides it's own description.
2201 (format "\n<text:bookmark text:name=\"%s\"/>" label)
2202 ;; Label definition: Typically formatted as below:
2203 ;; CATEGORY SEQ-NO: LONG CAPTION
2204 (format-spec
2205 (cadr (assoc-string label-style org-odt-label-styles t))
2206 `((?e . ,category)
2207 (?n . ,(format
2208 "<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">%s</text:sequence>"
2209 label counter counter seqno))
2210 (?c . ,(or caption "")))))
2211 short-caption))
2212 ;; Case 2: Handle Label reference.
2213 (reference
2214 (assert label)
2215 (setq label (org-export-solidify-link-text label))
2216 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2217 (fmt1 (car fmt))
2218 (fmt2 (cadr fmt)))
2219 (format "<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:sequence-ref>"
2220 fmt1 label (format-spec fmt2 `((?e . ,category)
2221 (?n . ,seqno))))))
2222 (t (error "Unknown %S on label" op))))))))
2225 ;;;; Links :: Inline Images
2227 (defun org-odt--copy-image-file (path)
2228 "Returns the internal name of the file"
2229 (let* ((image-type (file-name-extension path))
2230 (media-type (format "image/%s" image-type))
2231 (target-dir "Images/")
2232 (target-file
2233 (format "%s%04d.%s" target-dir
2234 (incf org-odt-embedded-images-count) image-type)))
2235 (message "Embedding %s as %s ..."
2236 (substring-no-properties path) target-file)
2238 (when (= 1 org-odt-embedded-images-count)
2239 (make-directory (concat org-odt-zip-dir target-dir))
2240 (org-odt-create-manifest-file-entry "" target-dir))
2242 (copy-file path (concat org-odt-zip-dir target-file) 'overwrite)
2243 (org-odt-create-manifest-file-entry media-type target-file)
2244 target-file))
2246 (defun org-odt--image-size (file &optional user-width
2247 user-height scale dpi embed-as)
2248 (let* ((--pixels-to-cms
2249 (function (lambda (pixels dpi)
2250 (let ((cms-per-inch 2.54)
2251 (inches (/ pixels dpi)))
2252 (* cms-per-inch inches)))))
2253 (--size-in-cms
2254 (function
2255 (lambda (size-in-pixels dpi)
2256 (and size-in-pixels
2257 (cons (funcall --pixels-to-cms (car size-in-pixels) dpi)
2258 (funcall --pixels-to-cms (cdr size-in-pixels) dpi))))))
2259 (dpi (or dpi org-odt-pixels-per-inch))
2260 (anchor-type (or embed-as "paragraph"))
2261 (user-width (and (not scale) user-width))
2262 (user-height (and (not scale) user-height))
2263 (size
2264 (and
2265 (not (and user-height user-width))
2267 ;; Use Imagemagick.
2268 (and (executable-find "identify")
2269 (let ((size-in-pixels
2270 (let ((dim (shell-command-to-string
2271 (format "identify -format \"%%w:%%h\" \"%s\""
2272 file))))
2273 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
2274 (cons (string-to-number (match-string 1 dim))
2275 (string-to-number (match-string 2 dim)))))))
2276 (funcall --size-in-cms size-in-pixels dpi)))
2277 ;; Use Emacs.
2278 (let ((size-in-pixels
2279 (ignore-errors ; Emacs could be in batch mode
2280 (clear-image-cache)
2281 (image-size (create-image file) 'pixels))))
2282 (funcall --size-in-cms size-in-pixels dpi))
2283 ;; Use hard-coded values.
2284 (cdr (assoc-string anchor-type
2285 org-odt-default-image-sizes-alist))
2286 ;; Error out.
2287 (error "Cannot determine image size, aborting"))))
2288 (width (car size)) (height (cdr size)))
2289 (cond
2290 (scale
2291 (setq width (* width scale) height (* height scale)))
2292 ((and user-height user-width)
2293 (setq width user-width height user-height))
2294 (user-height
2295 (setq width (* user-height (/ width height)) height user-height))
2296 (user-width
2297 (setq height (* user-width (/ height width)) width user-width))
2298 (t (ignore)))
2299 ;; ensure that an embedded image fits comfortably within a page
2300 (let ((max-width (car org-odt-max-image-size))
2301 (max-height (cdr org-odt-max-image-size)))
2302 (when (or (> width max-width) (> height max-height))
2303 (let* ((scale1 (/ max-width width))
2304 (scale2 (/ max-height height))
2305 (scale (min scale1 scale2)))
2306 (setq width (* scale width) height (* scale height)))))
2307 (cons width height)))
2309 (defun org-odt-link--inline-image (element info)
2310 "Return ODT code for an inline image.
2311 LINK is the link pointing to the inline image. INFO is a plist
2312 used as a communication channel."
2313 (assert (eq (org-element-type element) 'link))
2314 (let* ((src (let* ((type (org-element-property :type element))
2315 (raw-path (org-element-property :path element)))
2316 (cond ((member type '("http" "https"))
2317 (concat type ":" raw-path))
2318 ((file-name-absolute-p raw-path)
2319 (expand-file-name raw-path))
2320 (t raw-path))))
2321 (src-expanded (if (file-name-absolute-p src) src
2322 (expand-file-name src (file-name-directory
2323 (plist-get info :input-file)))))
2324 (href (format
2325 "\n<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
2326 (org-odt--copy-image-file src-expanded)))
2327 ;; Extract attributes from #+ATTR_ODT line.
2328 (attr-from (case (org-element-type element)
2329 (link (org-export-get-parent-element element))
2330 (t element)))
2331 ;; Convert attributes to a plist.
2332 (attr-plist (org-export-read-attribute :attr_odt attr-from))
2333 ;; Handle `:anchor', `:style' and `:attributes' properties.
2334 (user-frame-anchor
2335 (car (assoc-string (plist-get attr-plist :anchor)
2336 '(("as-char") ("paragraph") ("page")) t)))
2337 (user-frame-style
2338 (and user-frame-anchor (plist-get attr-plist :style)))
2339 (user-frame-attrs
2340 (and user-frame-anchor (plist-get attr-plist :attributes)))
2341 (user-frame-params
2342 (list user-frame-style user-frame-attrs user-frame-anchor))
2343 ;; (embed-as (or embed-as user-frame-anchor "paragraph"))
2344 ;; extrac
2346 ;; Handle `:width', `:height' and `:scale' properties. Read
2347 ;; them as numbers since we need them for computations.
2348 (size (org-odt--image-size
2349 src-expanded
2350 (let ((width (plist-get attr-plist :width)))
2351 (and width (read width)))
2352 (let ((length (plist-get attr-plist :length)))
2353 (and length (read length)))
2354 (let ((scale (plist-get attr-plist :scale)))
2355 (and scale (read scale)))
2356 nil ; embed-as
2357 "paragraph" ; FIXME
2359 (width (car size)) (height (cdr size))
2360 (standalone-link-p (org-odt--standalone-link-p element info))
2361 (embed-as (if standalone-link-p "paragraph" "as-char"))
2362 (captions (org-odt-format-label element info 'definition))
2363 (caption (car captions)) (short-caption (cdr captions))
2364 (entity (concat (and caption "Captioned") embed-as "Image"))
2365 ;; Check if this link was created by LaTeX-to-PNG converter.
2366 (replaces (org-element-property
2367 :replaces (if (not standalone-link-p) element
2368 (org-export-get-parent-element element))))
2369 ;; If yes, note down the type of the element - LaTeX Fragment
2370 ;; or LaTeX environment. It will go in to frame title.
2371 (title (and replaces (capitalize
2372 (symbol-name (org-element-type replaces)))))
2374 ;; If yes, note down it's contents. It will go in to frame
2375 ;; description. This quite useful for debugging.
2376 (desc (and replaces (org-element-property :value replaces))))
2377 (org-odt--render-image/formula entity href width height
2378 captions user-frame-params title desc)))
2381 ;;;; Links :: Math formula
2383 (defun org-odt-link--inline-formula (element info)
2384 (let* ((src (let* ((type (org-element-property :type element))
2385 (raw-path (org-element-property :path element)))
2386 (cond
2387 ((file-name-absolute-p raw-path)
2388 (expand-file-name raw-path))
2389 (t raw-path))))
2390 (src-expanded (if (file-name-absolute-p src) src
2391 (expand-file-name src (file-name-directory
2392 (plist-get info :input-file)))))
2393 (href
2394 (format
2395 "\n<draw:object %s xlink:href=\"%s\" xlink:type=\"simple\"/>"
2396 " xlink:show=\"embed\" xlink:actuate=\"onLoad\""
2397 (file-name-directory (org-odt--copy-formula-file src-expanded))))
2398 (standalone-link-p (org-odt--standalone-link-p element info))
2399 (embed-as (if standalone-link-p 'paragraph 'character))
2400 (captions (org-odt-format-label element info 'definition))
2401 (caption (car captions)) (short-caption (cdr captions))
2402 ;; Check if this link was created by LaTeX-to-MathML
2403 ;; converter.
2404 (replaces (org-element-property
2405 :replaces (if (not standalone-link-p) element
2406 (org-export-get-parent-element element))))
2407 ;; If yes, note down the type of the element - LaTeX Fragment
2408 ;; or LaTeX environment. It will go in to frame title.
2409 (title (and replaces (capitalize
2410 (symbol-name (org-element-type replaces)))))
2412 ;; If yes, note down it's contents. It will go in to frame
2413 ;; description. This quite useful for debugging.
2414 (desc (and replaces (org-element-property :value replaces)))
2415 width height)
2416 (cond
2417 ((eq embed-as 'character)
2418 (org-odt--render-image/formula "InlineFormula" href width height
2419 nil nil title desc))
2421 (let* ((equation (org-odt--render-image/formula
2422 "CaptionedDisplayFormula" href width height
2423 captions nil title desc))
2424 (label
2425 (let* ((org-odt-category-map-alist
2426 '(("__MathFormula__" "Text" "math-label" "Equation"
2427 org-odt--enumerable-formula-p))))
2428 (car (org-odt-format-label element info 'definition)))))
2429 (concat equation "<text:tab/>" label))))))
2431 (defun org-odt--copy-formula-file (src-file)
2432 "Returns the internal name of the file"
2433 (let* ((target-dir (format "Formula-%04d/"
2434 (incf org-odt-embedded-formulas-count)))
2435 (target-file (concat target-dir "content.xml")))
2436 ;; Create a directory for holding formula file. Also enter it in
2437 ;; to manifest.
2438 (make-directory (concat org-odt-zip-dir target-dir))
2439 (org-odt-create-manifest-file-entry
2440 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
2441 ;; Copy over the formula file from user directory to zip
2442 ;; directory.
2443 (message "Embedding %s as %s ..." src-file target-file)
2444 (let ((case-fold-search nil))
2445 (cond
2446 ;; Case 1: Mathml.
2447 ((string-match "\\.\\(mathml\\|mml\\)\\'" src-file)
2448 (copy-file src-file (concat org-odt-zip-dir target-file) 'overwrite))
2449 ;; Case 2: OpenDocument formula.
2450 ((string-match "\\.odf\\'" src-file)
2451 (org-odt--zip-extract src-file "content.xml"
2452 (concat org-odt-zip-dir target-dir)))
2453 (t (error "%s is not a formula file" src-file))))
2454 ;; Enter the formula file in to manifest.
2455 (org-odt-create-manifest-file-entry "text/xml" target-file)
2456 target-file))
2458 ;;;; Targets
2460 (defun org-odt--render-image/formula (cfg-key href width height &optional
2461 captions user-frame-params
2462 &rest title-and-desc)
2463 (let* ((frame-cfg-alist
2464 ;; Each element of this alist is of the form (CFG-HANDLE
2465 ;; INNER-FRAME-PARAMS OUTER-FRAME-PARAMS).
2467 ;; CFG-HANDLE is the key to the alist.
2469 ;; INNER-FRAME-PARAMS and OUTER-FRAME-PARAMS specify the
2470 ;; frame params for INNER-FRAME and OUTER-FRAME
2471 ;; respectively. See below.
2473 ;; Configurations that are meant to be applied to
2474 ;; non-captioned image/formula specifies no
2475 ;; OUTER-FRAME-PARAMS.
2477 ;; TERMINOLOGY
2478 ;; ===========
2479 ;; INNER-FRAME :: Frame that directly surrounds an
2480 ;; image/formula.
2482 ;; OUTER-FRAME :: Frame that encloses the INNER-FRAME. This
2483 ;; frame also contains the caption, if any.
2485 ;; FRAME-PARAMS :: List of the form (FRAME-STYLE-NAME
2486 ;; FRAME-ATTRIBUTES FRAME-ANCHOR). Note
2487 ;; that these are the last three arguments
2488 ;; to `org-odt--frame'.
2490 ;; Note that an un-captioned image/formula requires just an
2491 ;; INNER-FRAME, while a captioned image/formula requires
2492 ;; both an INNER and an OUTER-FRAME.
2493 '(("As-CharImage" ("OrgInlineImage" nil "as-char"))
2494 ("ParagraphImage" ("OrgDisplayImage" nil "paragraph"))
2495 ("PageImage" ("OrgPageImage" nil "page"))
2496 ("CaptionedAs-CharImage"
2497 ("OrgCaptionedImage"
2498 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2499 ("OrgInlineImage" nil "as-char"))
2500 ("CaptionedParagraphImage"
2501 ("OrgCaptionedImage"
2502 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2503 ("OrgImageCaptionFrame" nil "paragraph"))
2504 ("CaptionedPageImage"
2505 ("OrgCaptionedImage"
2506 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2507 ("OrgPageImageCaptionFrame" nil "page"))
2508 ("InlineFormula" ("OrgInlineFormula" nil "as-char"))
2509 ("DisplayFormula" ("OrgDisplayFormula" nil "as-char"))
2510 ("CaptionedDisplayFormula"
2511 ("OrgCaptionedFormula" nil "paragraph")
2512 ("OrgFormulaCaptionFrame" nil "paragraph"))))
2513 (caption (car captions)) (short-caption (cdr captions))
2514 ;; Retrieve inner and outer frame params, from configuration.
2515 (frame-cfg (assoc-string cfg-key frame-cfg-alist t))
2516 (inner (nth 1 frame-cfg))
2517 (outer (nth 2 frame-cfg))
2518 ;; User-specified frame params (from #+ATTR_ODT spec)
2519 (user user-frame-params)
2520 (--merge-frame-params (function
2521 (lambda (default user)
2522 "Merge default and user frame params."
2523 (if (not user) default
2524 (assert (= (length default) 3))
2525 (assert (= (length user) 3))
2526 (loop for u in user
2527 for d in default
2528 collect (or u d)))))))
2529 (cond
2530 ;; Case 1: Image/Formula has no caption.
2531 ;; There is only one frame, one that surrounds the image
2532 ;; or formula.
2533 ((not caption)
2534 ;; Merge user frame params with that from configuration.
2535 (setq inner (funcall --merge-frame-params inner user))
2536 (apply 'org-odt--frame href width height
2537 (append inner title-and-desc)))
2538 ;; Case 2: Image/Formula is captioned or labeled.
2539 ;; There are two frames: The inner one surrounds the
2540 ;; image or formula. The outer one contains the
2541 ;; caption/sequence number.
2543 ;; Merge user frame params with outer frame params.
2544 (setq outer (funcall --merge-frame-params outer user))
2545 ;; Short caption, if specified, goes as part of inner frame.
2546 (setq inner (let ((frame-params (copy-sequence inner)))
2547 (setcar (cdr frame-params)
2548 (concat
2549 (cadr frame-params)
2550 (when short-caption
2551 (format " draw:name=\"%s\" " short-caption))))
2552 frame-params))
2553 (apply 'org-odt--textbox
2554 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2555 "Illustration"
2556 (concat
2557 (apply 'org-odt--frame href width height
2558 (append inner title-and-desc))
2559 caption))
2560 width height outer)))))
2562 (defun org-odt--enumerable-p (element info)
2563 ;; Element should have a caption or label.
2564 (or (org-element-property :caption element)
2565 (org-element-property :name element)))
2567 (defun org-odt--enumerable-image-p (element info)
2568 (org-odt--standalone-link-p
2569 element info
2570 ;; Paragraph should have a caption or label. It SHOULD NOT be a
2571 ;; replacement element. (i.e., It SHOULD NOT be a result of LaTeX
2572 ;; processing.)
2573 (lambda (p)
2574 (and (not (org-element-property :replaces p))
2575 (or (org-element-property :caption p)
2576 (org-element-property :name p))))
2577 ;; Link should point to an image file.
2578 (lambda (l)
2579 (assert (eq (org-element-type l) 'link))
2580 (org-export-inline-image-p l org-odt-inline-image-rules))))
2582 (defun org-odt--enumerable-latex-image-p (element info)
2583 (org-odt--standalone-link-p
2584 element info
2585 ;; Paragraph should have a caption or label. It SHOULD also be a
2586 ;; replacement element. (i.e., It SHOULD be a result of LaTeX
2587 ;; processing.)
2588 (lambda (p)
2589 (and (org-element-property :replaces p)
2590 (or (org-element-property :caption p)
2591 (org-element-property :name p))))
2592 ;; Link should point to an image file.
2593 (lambda (l)
2594 (assert (eq (org-element-type l) 'link))
2595 (org-export-inline-image-p l org-odt-inline-image-rules))))
2597 (defun org-odt--enumerable-formula-p (element info)
2598 (org-odt--standalone-link-p
2599 element info
2600 ;; Paragraph should have a caption or label.
2601 (lambda (p)
2602 (or (org-element-property :caption p)
2603 (org-element-property :name p)))
2604 ;; Link should point to a MathML or ODF file.
2605 (lambda (l)
2606 (assert (eq (org-element-type l) 'link))
2607 (org-export-inline-image-p l org-odt-inline-formula-rules))))
2609 (defun org-odt--standalone-link-p (element info &optional
2610 paragraph-predicate
2611 link-predicate)
2612 "Test if ELEMENT is a standalone link for the purpose ODT export.
2613 INFO is a plist holding contextual information.
2615 Return non-nil, if ELEMENT is of type paragraph satisfying
2616 PARAGRAPH-PREDICATE and it's sole content, save for whitespaces,
2617 is a link that satisfies LINK-PREDICATE.
2619 Return non-nil, if ELEMENT is of type link satisfying
2620 LINK-PREDICATE and it's containing paragraph satisfies
2621 PARAGRAPH-PREDICATE inaddtion to having no other content save for
2622 leading and trailing whitespaces.
2624 Return nil, otherwise."
2625 (let ((p (case (org-element-type element)
2626 (paragraph element)
2627 (link (and (or (not link-predicate)
2628 (funcall link-predicate element))
2629 (org-export-get-parent element)))
2630 (t nil))))
2631 (when (and p (eq (org-element-type p) 'paragraph))
2632 (when (or (not paragraph-predicate)
2633 (funcall paragraph-predicate p))
2634 (let ((contents (org-element-contents p)))
2635 (loop for x in contents
2636 with inline-image-count = 0
2637 always (case (org-element-type x)
2638 (plain-text
2639 (not (org-string-nw-p x)))
2640 (link
2641 (and (or (not link-predicate)
2642 (funcall link-predicate x))
2643 (= (incf inline-image-count) 1)))
2644 (t nil))))))))
2646 (defun org-odt-link--infer-description (destination info)
2647 ;; DESTINATION is a HEADLINE, a "<<target>>" or an element (like
2648 ;; paragraph, verse-block etc) to which a "#+NAME: label" can be
2649 ;; attached. Note that labels that are attached to captioned
2650 ;; entities - inline images, math formulae and tables - get resolved
2651 ;; as part of `org-odt-format-label' and `org-odt--enumerate'.
2653 ;; Create a cross-reference to DESTINATION but make best-efforts to
2654 ;; create a *meaningful* description. Check item numbers, section
2655 ;; number and section title in that order.
2657 ;; NOTE: Counterpart of `org-export-get-ordinal'.
2658 ;; FIXME: Handle footnote-definition footnote-reference?
2659 (let* ((genealogy (org-export-get-genealogy destination))
2660 (data (reverse genealogy))
2661 (label (case (org-element-type destination)
2662 (headline
2663 (format "sec-%s" (mapconcat 'number-to-string
2664 (org-export-get-headline-number
2665 destination info) "-")))
2666 (target
2667 (org-element-property :value destination))
2668 (t (error "FIXME: Resolve %S" destination)))))
2670 (let* ( ;; Locate top-level list.
2671 (top-level-list
2672 (loop for x on data
2673 when (eq (org-element-type (car x)) 'plain-list)
2674 return x))
2675 ;; Get list item nos.
2676 (item-numbers
2677 (loop for (plain-list item . rest) on top-level-list by #'cddr
2678 until (not (eq (org-element-type plain-list) 'plain-list))
2679 collect (when (eq (org-element-property :type
2680 plain-list)
2681 'ordered)
2682 (1+ (length (org-export-get-previous-element
2683 item info t))))))
2684 ;; Locate top-most listified headline.
2685 (listified-headlines
2686 (loop for x on data
2687 when (and (eq (org-element-type (car x)) 'headline)
2688 (org-export-low-level-p (car x) info))
2689 return x))
2690 ;; Get listified headline numbers.
2691 (listified-headline-nos
2692 (loop for el in listified-headlines
2693 when (eq (org-element-type el) 'headline)
2694 collect (when (org-export-numbered-headline-p el info)
2695 (1+ (length (org-export-get-previous-element
2696 el info t)))))))
2697 ;; Combine item numbers from both the listified headlines and
2698 ;; regular list items.
2700 ;; Case 1: Check if all the parents of list item are numbered.
2701 ;; If yes, link to the item proper.
2702 (let ((item-numbers (append listified-headline-nos item-numbers)))
2703 (when (and item-numbers (not (memq nil item-numbers)))
2704 (format "<text:bookmark-ref text:reference-format=\"number-all-superior\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2705 (org-export-solidify-link-text label)
2706 (mapconcat (lambda (n) (if (not n) " "
2707 (concat (number-to-string n) ".")))
2708 item-numbers "")))))
2709 ;; Case 2: Locate a regular and numbered headline in the
2710 ;; hierarchy. Display it's section number.
2711 (let ((headline (loop for el in (cons destination genealogy)
2712 when (and (eq (org-element-type el) 'headline)
2713 (not (org-export-low-level-p el info))
2714 (org-export-numbered-headline-p el info))
2715 return el)))
2716 ;; We found one.
2717 (when headline
2718 (format "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2719 (org-export-solidify-link-text label)
2720 (mapconcat 'number-to-string (org-export-get-headline-number
2721 headline info) "."))))
2722 ;; Case 4: Locate a regular headline in the hierarchy. Display
2723 ;; it's title.
2724 (let ((headline (loop for el in (cons destination genealogy)
2725 when (and (eq (org-element-type el) 'headline)
2726 (not (org-export-low-level-p el info)))
2727 return el)))
2728 ;; We found one.
2729 (when headline
2730 (format "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2731 (org-export-solidify-link-text label)
2732 (let ((title (org-element-property :title headline)))
2733 (org-export-data title info)))))
2734 (error "FIXME?"))))
2736 (defun org-odt-link (link desc info)
2737 "Transcode a LINK object from Org to ODT.
2739 DESC is the description part of the link, or the empty string.
2740 INFO is a plist holding contextual information. See
2741 `org-export-data'."
2742 (let* ((type (org-element-property :type link))
2743 (raw-path (org-element-property :path link))
2744 ;; Ensure DESC really exists, or set it to nil.
2745 (desc (and (not (string= desc "")) desc))
2746 (imagep (org-export-inline-image-p
2747 link org-odt-inline-image-rules))
2748 (path (cond
2749 ((member type '("http" "https" "ftp" "mailto"))
2750 (concat type ":" raw-path))
2751 ((string= type "file")
2752 (if (file-name-absolute-p raw-path)
2753 (concat "file://" (expand-file-name raw-path))
2754 (concat "file://" raw-path)))
2755 (t raw-path)))
2756 protocol)
2757 (cond
2758 ;; Image file.
2759 ((and (not desc) (org-export-inline-image-p
2760 link org-odt-inline-image-rules))
2761 (org-odt-link--inline-image link info))
2762 ;; Formula file.
2763 ((and (not desc) (org-export-inline-image-p
2764 link org-odt-inline-formula-rules))
2765 (org-odt-link--inline-formula link info))
2766 ;; Radio target: Transcode target's contents and use them as
2767 ;; link's description.
2768 ((string= type "radio")
2769 (let ((destination (org-export-resolve-radio-link link info)))
2770 (when destination
2771 (let ((desc (org-export-data (org-element-contents destination) info))
2772 (href (org-export-solidify-link-text path)))
2773 (format
2774 "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2775 href desc)))))
2776 ;; Links pointing to a headline: Find destination and build
2777 ;; appropriate referencing command.
2778 ((member type '("custom-id" "fuzzy" "id"))
2779 (let* ((destination (if (string= type "fuzzy")
2780 (org-export-resolve-fuzzy-link link info)
2781 (org-export-resolve-id-link link info))))
2783 ;; Case 1: Fuzzy link points nowhere.
2784 (when (null (org-element-type destination))
2785 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2786 "Emphasis" (or desc (org-export-data
2787 (org-element-property
2788 :raw-link link) info))))
2789 ;; Case 2: Fuzzy link points to an invisible target. Strip it.
2790 (when (eq (org-element-type destination) 'keyword) "")
2791 ;; Case 3: LINK points to a headline.
2792 (when (eq (org-element-type destination) 'headline)
2793 ;; Case 3.1: LINK has a custom description that is
2794 ;; different from headline's title. Create a hyperlink.
2795 (when (and desc
2796 (let ((link-desc (org-element-contents link)))
2797 (not (string= (org-element-interpret-data link-desc)
2798 (org-element-property :raw-value
2799 destination)))))
2800 (let* ((headline-no (org-export-get-headline-number
2801 destination info))
2802 (label (format "sec-%s" (mapconcat 'number-to-string
2803 headline-no "-"))))
2804 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2805 label desc))))
2806 ;; Case 4: LINK points to an Inline image, Math formula or a Table.
2807 (let ((label-reference (ignore-errors (org-odt-format-label
2808 destination info 'reference))))
2809 (when label-reference
2810 (cond
2811 ;; Case 4.1: LINK has no description. Create a
2812 ;; cross-reference showing entity's sequence number.
2813 ((not desc) label-reference)
2814 ;; Case 4.2: LINK has description. Insert a hyperlink
2815 ;; with user-provided description.
2816 (t (let* ((caption-from (case (org-element-type destination)
2817 (link (org-export-get-parent-element
2818 destination))
2819 (t destination)))
2820 ;; Get label and caption.
2821 (label (org-element-property :name caption-from)))
2822 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2823 (org-export-solidify-link-text label) desc))))))
2824 ;; Case 5: Fuzzy link points to a TARGET.
2825 (when (eq (org-element-type destination) 'target)
2826 ;; Case 5.1: LINK has description. Create a hyperlink.
2827 (when desc
2828 (let ((label (org-element-property :value destination)))
2829 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2830 (org-export-solidify-link-text label) desc))))
2831 ;; LINK has no description. It points to either a HEADLINE, a
2832 ;; TARGET or an ELEMENT with a #+NAME: LABEL attached to it.
2833 ;; LINK to DESTINATION, but make a best effort to provide a
2834 ;; *meaningful* description.
2835 (org-odt-link--infer-description destination info))))
2836 ;; Coderef: replace link with the reference name or the
2837 ;; equivalent line number.
2838 ((string= type "coderef")
2839 (let* ((line-no (format "%d" (org-export-resolve-coderef path info)))
2840 (href (concat "coderef-" path)))
2841 (format
2842 (org-export-get-coderef-format path desc)
2843 (format
2844 "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2845 href line-no))))
2846 ;; Link type is handled by a special function.
2847 ((functionp (setq protocol (nth 2 (assoc type org-link-protocols))))
2848 (funcall protocol (org-link-unescape path) desc 'odt))
2849 ;; External link with a description part.
2850 ((and path desc)
2851 (let ((link-contents (org-element-contents link)))
2852 ;; Check if description is a link to an inline image.
2853 (if (and (not (cdr link-contents))
2854 (let ((desc-element (car link-contents)))
2855 (and (eq (org-element-type desc-element) 'link)
2856 (org-export-inline-image-p
2857 desc-element org-odt-inline-image-rules))))
2858 ;; Format link as a clickable image.
2859 (format "\n<draw:a xlink:type=\"simple\" xlink:href=\"%s\">\n%s\n</draw:a>"
2860 path desc)
2861 ;; Otherwise, format it as a regular link.
2862 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2863 path desc))))
2864 ;; External link without a description part.
2865 (path
2866 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2867 path path))
2868 ;; No path, only description. Try to do something useful.
2869 (t (format "<text:span text:style-name=\"%s\">%s</text:span>"
2870 "Emphasis" desc)))))
2873 ;;;; Paragraph
2875 (defun org-odt-paragraph (paragraph contents info)
2876 "Transcode a PARAGRAPH element from Org to ODT.
2877 CONTENTS is the contents of the paragraph, as a string. INFO is
2878 the plist used as a communication channel."
2879 (let* ((parent (org-export-get-parent paragraph))
2880 (parent-type (org-element-type parent))
2881 (style (case parent-type
2882 (quote-block "Quotations")
2883 (center-block "OrgCenter")
2884 (footnote-definition "Footnote")
2885 (t (or (org-element-property :style paragraph)
2886 "Text_20_body")))))
2887 ;; If this paragraph is a leading paragraph in an item and the
2888 ;; item has a checkbox, splice the checkbox and paragraph contents
2889 ;; together.
2890 (when (and (eq (org-element-type parent) 'item)
2891 (eq paragraph (car (org-element-contents parent))))
2892 (setq contents (concat (org-odt--checkbox parent) contents)))
2893 (assert style)
2894 (format "\n<text:p text:style-name=\"%s\">%s</text:p>" style contents)))
2897 ;;;; Plain List
2899 (defun org-odt-plain-list (plain-list contents info)
2900 "Transcode a PLAIN-LIST element from Org to ODT.
2901 CONTENTS is the contents of the list. INFO is a plist holding
2902 contextual information."
2903 (format "\n<text:list text:style-name=\"%s\" %s>\n%s</text:list>"
2904 ;; Choose style based on list type.
2905 (case (org-element-property :type plain-list)
2906 (ordered "OrgNumberedList")
2907 (unordered "OrgBulletedList")
2908 (descriptive-1 "OrgDescriptionList")
2909 (descriptive-2 "OrgDescriptionList"))
2910 ;; If top-level list, re-start numbering. Otherwise,
2911 ;; continue numbering.
2912 (format "text:continue-numbering=\"%s\""
2913 (let* ((parent (org-export-get-parent plain-list)))
2914 (if (and parent (eq (org-element-type parent) 'item))
2915 "true" "false")))
2916 contents))
2918 ;;;; Plain Text
2920 (defun org-odt--encode-tabs-and-spaces (line)
2921 (replace-regexp-in-string
2922 "\\([\t]\\|\\([ ]+\\)\\)"
2923 (lambda (s)
2924 (cond
2925 ((string= s "\t") "<text:tab/>")
2926 (t (let ((n (length s)))
2927 (cond
2928 ((= n 1) " ")
2929 ((> n 1) (concat " " (format "<text:s text:c=\"%d\"/>" (1- n))))
2930 (t ""))))))
2931 line))
2933 (defun org-odt--encode-plain-text (text &optional no-whitespace-filling)
2934 (mapc
2935 (lambda (pair)
2936 (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t)))
2937 '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2938 (if no-whitespace-filling text
2939 (org-odt--encode-tabs-and-spaces text)))
2941 (defun org-odt-plain-text (text info)
2942 "Transcode a TEXT string from Org to ODT.
2943 TEXT is the string to transcode. INFO is a plist holding
2944 contextual information."
2945 (let ((output text))
2946 ;; Protect &, < and >.
2947 (setq output (org-odt--encode-plain-text output t))
2948 ;; Handle smart quotes. Be sure to provide original string since
2949 ;; OUTPUT may have been modified.
2950 (setq output (org-export-activate-smart-quotes output :utf-8 info text))
2951 ;; Convert special strings.
2952 (when (plist-get info :with-special-strings)
2953 (mapc
2954 (lambda (pair)
2955 (setq output
2956 (replace-regexp-in-string (car pair) (cdr pair) output t nil)))
2957 org-odt-special-string-regexps))
2958 ;; Handle break preservation if required.
2959 (when (plist-get info :preserve-breaks)
2960 (setq output (replace-regexp-in-string
2961 "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>\n" output t)))
2962 ;; Return value.
2963 output))
2966 ;;;; Planning
2968 (defun org-odt-planning (planning contents info)
2969 "Transcode a PLANNING element from Org to ODT.
2970 CONTENTS is nil. INFO is a plist used as a communication
2971 channel."
2972 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2973 "OrgPlanning"
2974 (concat
2975 (let ((closed (org-element-property :closed planning)))
2976 (when closed
2977 (concat
2978 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2979 "OrgClosedKeyword" org-closed-string)
2980 (org-odt-timestamp closed contents info))))
2981 (let ((deadline (org-element-property :deadline planning)))
2982 (when deadline
2983 (concat
2984 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2985 "OrgDeadlineKeyword" org-deadline-string)
2986 (org-odt-timestamp deadline contents info))))
2987 (let ((scheduled (org-element-property :scheduled planning)))
2988 (when scheduled
2989 (concat
2990 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2991 "OrgScheduledKeyword" org-deadline-string)
2992 (org-odt-timestamp scheduled contents info)))))))
2995 ;;;; Property Drawer
2997 (defun org-odt-property-drawer (property-drawer contents info)
2998 "Transcode a PROPERTY-DRAWER element from Org to ODT.
2999 CONTENTS is nil. INFO is a plist holding contextual
3000 information."
3001 ;; The property drawer isn't exported but we want separating blank
3002 ;; lines nonetheless.
3006 ;;;; Quote Block
3008 (defun org-odt-quote-block (quote-block contents info)
3009 "Transcode a QUOTE-BLOCK element from Org to ODT.
3010 CONTENTS holds the contents of the block. INFO is a plist
3011 holding contextual information."
3012 contents)
3015 ;;;; Quote Section
3017 (defun org-odt-quote-section (quote-section contents info)
3018 "Transcode a QUOTE-SECTION element from Org to ODT.
3019 CONTENTS is nil. INFO is a plist holding contextual information."
3020 (let ((value (org-remove-indentation
3021 (org-element-property :value quote-section))))
3022 (when value (org-odt-do-format-code value))))
3025 ;;;; Section
3027 (defun org-odt-format-section (text style &optional name)
3028 (let ((default-name (car (org-odt-add-automatic-style "Section"))))
3029 (format "\n<text:section text:style-name=\"%s\" %s>\n%s\n</text:section>"
3030 style
3031 (format "text:name=\"%s\"" (or name default-name))
3032 text)))
3035 (defun org-odt-section (section contents info) ; FIXME
3036 "Transcode a SECTION element from Org to ODT.
3037 CONTENTS holds the contents of the section. INFO is a plist
3038 holding contextual information."
3039 contents)
3041 ;;;; Radio Target
3043 (defun org-odt-radio-target (radio-target text info)
3044 "Transcode a RADIO-TARGET object from Org to ODT.
3045 TEXT is the text of the target. INFO is a plist holding
3046 contextual information."
3047 (org-odt--target
3048 text (org-export-solidify-link-text
3049 (org-element-property :value radio-target))))
3052 ;;;; Special Block
3054 (defun org-odt-special-block (special-block contents info)
3055 "Transcode a SPECIAL-BLOCK element from Org to ODT.
3056 CONTENTS holds the contents of the block. INFO is a plist
3057 holding contextual information."
3058 (let ((type (downcase (org-element-property :type special-block)))
3059 (attributes (org-export-read-attribute :attr_odt special-block)))
3060 (cond
3061 ;; Annotation.
3062 ((string= type "annotation")
3063 (let* ((author (or (plist-get attributes :author)
3064 (let ((author (plist-get info :author)))
3065 (and author (org-export-data author info)))))
3066 (date (or (plist-get attributes :date)
3067 ;; FIXME: Is `car' right thing to do below?
3068 (car (plist-get info :date)))))
3069 (format "\n<text:p>%s</text:p>"
3070 (format "<office:annotation>\n%s\n</office:annotation>"
3071 (concat
3072 (and author
3073 (format "<dc:creator>%s</dc:creator>" author))
3074 (and date
3075 (format "<dc:date>%s</dc:date>"
3076 (org-odt--format-timestamp date nil 'iso-date)))
3077 contents)))))
3078 ;; Textbox.
3079 ((string= type "textbox")
3080 (let ((width (plist-get attributes :width))
3081 (height (plist-get attributes :height))
3082 (style (plist-get attributes :style))
3083 (extra (plist-get attributes :extra))
3084 (anchor (plist-get attributes :anchor)))
3085 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3086 "Text_20_body" (org-odt--textbox contents width height
3087 style extra anchor))))
3088 (t contents))))
3091 ;;;; Src Block
3093 (defun org-odt-hfy-face-to-css (fn)
3094 "Create custom style for face FN.
3095 When FN is the default face, use it's foreground and background
3096 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
3097 use it's color attribute to create a character style whose name
3098 is obtained from FN. Currently all attributes of FN other than
3099 color are ignored.
3101 The style name for a face FN is derived using the following
3102 operations on the face name in that order - de-dash, CamelCase
3103 and prefix with \"OrgSrc\". For example,
3104 `font-lock-function-name-face' is associated with
3105 \"OrgSrcFontLockFunctionNameFace\"."
3106 (let* ((css-list (hfy-face-to-style fn))
3107 (style-name ((lambda (fn)
3108 (concat "OrgSrc"
3109 (mapconcat
3110 'capitalize (split-string
3111 (hfy-face-or-def-to-name fn) "-")
3112 ""))) fn))
3113 (color-val (cdr (assoc "color" css-list)))
3114 (background-color-val (cdr (assoc "background" css-list)))
3115 (style (and org-odt-create-custom-styles-for-srcblocks
3116 (cond
3117 ((eq fn 'default)
3118 (format org-odt-src-block-paragraph-format
3119 background-color-val color-val))
3121 (format
3123 <style:style style:name=\"%s\" style:family=\"text\">
3124 <style:text-properties fo:color=\"%s\"/>
3125 </style:style>" style-name color-val))))))
3126 (cons style-name style)))
3128 (defun org-odt-htmlfontify-string (line)
3129 (let* ((hfy-html-quote-regex "\\([<\"&> ]\\)")
3130 (hfy-html-quote-map '(("\"" "&quot;")
3131 ("<" "&lt;")
3132 ("&" "&amp;")
3133 (">" "&gt;")
3134 (" " "<text:s/>")
3135 (" " "<text:tab/>")))
3136 (hfy-face-to-css 'org-odt-hfy-face-to-css)
3137 (hfy-optimisations-1 (copy-sequence hfy-optimisations))
3138 (hfy-optimisations (add-to-list 'hfy-optimisations-1
3139 'body-text-only))
3140 (hfy-begin-span-handler
3141 (lambda (style text-block text-id text-begins-block-p)
3142 (insert (format "<text:span text:style-name=\"%s\">" style))))
3143 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
3144 (org-no-warnings (htmlfontify-string line))))
3146 (defun org-odt-do-format-code
3147 (code &optional lang refs retain-labels num-start)
3148 (let* ((lang (or (assoc-default lang org-src-lang-modes) lang))
3149 (lang-mode (and lang (intern (format "%s-mode" lang))))
3150 (code-lines (org-split-string code "\n"))
3151 (code-length (length code-lines))
3152 (use-htmlfontify-p (and (functionp lang-mode)
3153 org-odt-fontify-srcblocks
3154 (require 'htmlfontify nil t)
3155 (fboundp 'htmlfontify-string)))
3156 (code (if (not use-htmlfontify-p) code
3157 (with-temp-buffer
3158 (insert code)
3159 (funcall lang-mode)
3160 (font-lock-fontify-buffer)
3161 (buffer-string))))
3162 (fontifier (if use-htmlfontify-p 'org-odt-htmlfontify-string
3163 'org-odt--encode-plain-text))
3164 (par-style (if use-htmlfontify-p "OrgSrcBlock"
3165 "OrgFixedWidthBlock"))
3166 (i 0))
3167 (assert (= code-length (length (org-split-string code "\n"))))
3168 (setq code
3169 (org-export-format-code
3170 code
3171 (lambda (loc line-num ref)
3172 (setq par-style
3173 (concat par-style (and (= (incf i) code-length) "LastLine")))
3175 (setq loc (concat loc (and ref retain-labels (format " (%s)" ref))))
3176 (setq loc (funcall fontifier loc))
3177 (when ref
3178 (setq loc (org-odt--target loc (concat "coderef-" ref))))
3179 (assert par-style)
3180 (setq loc (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3181 par-style loc))
3182 (if (not line-num) loc
3183 (format "\n<text:list-item>%s\n</text:list-item>" loc)))
3184 num-start refs))
3185 (cond
3186 ((not num-start) code)
3187 ((= num-start 0)
3188 (format
3189 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3190 " text:continue-numbering=\"false\"" code))
3192 (format
3193 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3194 " text:continue-numbering=\"true\"" code)))))
3196 (defun org-odt-format-code (element info)
3197 (let* ((lang (org-element-property :language element))
3198 ;; Extract code and references.
3199 (code-info (org-export-unravel-code element))
3200 (code (car code-info))
3201 (refs (cdr code-info))
3202 ;; Does the src block contain labels?
3203 (retain-labels (org-element-property :retain-labels element))
3204 ;; Does it have line numbers?
3205 (num-start (case (org-element-property :number-lines element)
3206 (continued (org-export-get-loc element info))
3207 (new 0))))
3208 (org-odt-do-format-code code lang refs retain-labels num-start)))
3210 (defun org-odt-src-block (src-block contents info)
3211 "Transcode a SRC-BLOCK element from Org to ODT.
3212 CONTENTS holds the contents of the item. INFO is a plist holding
3213 contextual information."
3214 (let* ((lang (org-element-property :language src-block))
3215 (attributes (org-export-read-attribute :attr_odt src-block))
3216 (captions (org-odt-format-label src-block info 'definition))
3217 (caption (car captions)) (short-caption (cdr captions)))
3218 (concat
3219 (and caption
3220 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3221 "Listing" caption))
3222 (let ((--src-block (org-odt-format-code src-block info)))
3223 (if (not (plist-get attributes :textbox)) --src-block
3224 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3225 "Text_20_body"
3226 (org-odt--textbox --src-block nil nil nil)))))))
3229 ;;;; Statistics Cookie
3231 (defun org-odt-statistics-cookie (statistics-cookie contents info)
3232 "Transcode a STATISTICS-COOKIE object from Org to ODT.
3233 CONTENTS is nil. INFO is a plist holding contextual information."
3234 (let ((cookie-value (org-element-property :value statistics-cookie)))
3235 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3236 "OrgCode" cookie-value)))
3239 ;;;; Strike-Through
3241 (defun org-odt-strike-through (strike-through contents info)
3242 "Transcode STRIKE-THROUGH from Org to ODT.
3243 CONTENTS is the text with strike-through markup. INFO is a plist
3244 holding contextual information."
3245 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3246 "Strikethrough" contents))
3249 ;;;; Subscript
3251 (defun org-odt-subscript (subscript contents info)
3252 "Transcode a SUBSCRIPT object from Org to ODT.
3253 CONTENTS is the contents of the object. INFO is a plist holding
3254 contextual information."
3255 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3256 "OrgSubscript" contents))
3259 ;;;; Superscript
3261 (defun org-odt-superscript (superscript contents info)
3262 "Transcode a SUPERSCRIPT object from Org to ODT.
3263 CONTENTS is the contents of the object. INFO is a plist holding
3264 contextual information."
3265 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3266 "OrgSuperscript" contents))
3269 ;;;; Table Cell
3271 (defun org-odt-table-style-spec (element info)
3272 (let* ((table (org-export-get-parent-table element))
3273 (table-attributes (org-export-read-attribute :attr_odt table))
3274 (table-style (plist-get table-attributes :style)))
3275 (assoc table-style org-odt-table-styles)))
3277 (defun org-odt-get-table-cell-styles (table-cell info)
3278 "Retrieve styles applicable to a table cell.
3279 R and C are (zero-based) row and column numbers of the table
3280 cell. STYLE-SPEC is an entry in `org-odt-table-styles'
3281 applicable to the current table. It is `nil' if the table is not
3282 associated with any style attributes.
3284 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
3286 When STYLE-SPEC is nil, style the table cell the conventional way
3287 - choose cell borders based on row and column groupings and
3288 choose paragraph alignment based on `org-col-cookies' text
3289 property. See also
3290 `org-odt-get-paragraph-style-cookie-for-table-cell'.
3292 When STYLE-SPEC is non-nil, ignore the above cookie and return
3293 styles congruent with the ODF-1.2 specification."
3294 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3295 (r (car table-cell-address)) (c (cdr table-cell-address))
3296 (style-spec (org-odt-table-style-spec table-cell info))
3297 (table-dimensions (org-export-table-dimensions
3298 (org-export-get-parent-table table-cell)
3299 info)))
3300 (when style-spec
3301 ;; LibreOffice - particularly the Writer - honors neither table
3302 ;; templates nor custom table-cell styles. Inorder to retain
3303 ;; inter-operability with LibreOffice, only automatic styles are
3304 ;; used for styling of table-cells. The current implementation is
3305 ;; congruent with ODF-1.2 specification and hence is
3306 ;; future-compatible.
3308 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
3309 ;; which recognizes as many as 16 different cell types - is much
3310 ;; richer. Unfortunately it is NOT amenable to easy configuration
3311 ;; by hand.
3312 (let* ((template-name (nth 1 style-spec))
3313 (cell-style-selectors (nth 2 style-spec))
3314 (cell-type
3315 (cond
3316 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
3317 (= c 0)) "FirstColumn")
3318 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
3319 (= (1+ c) (cdr table-dimensions)))
3320 "LastColumn")
3321 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
3322 (= r 0)) "FirstRow")
3323 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
3324 (= (1+ r) (car table-dimensions)))
3325 "LastRow")
3326 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3327 (= (% r 2) 1)) "EvenRow")
3328 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3329 (= (% r 2) 0)) "OddRow")
3330 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3331 (= (% c 2) 1)) "EvenColumn")
3332 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3333 (= (% c 2) 0)) "OddColumn")
3334 (t ""))))
3335 (concat template-name cell-type)))))
3337 (defun org-odt-table-cell (table-cell contents info)
3338 "Transcode a TABLE-CELL element from Org to ODT.
3339 CONTENTS is nil. INFO is a plist used as a communication
3340 channel."
3341 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3342 (r (car table-cell-address))
3343 (c (cdr table-cell-address))
3344 (horiz-span (or (org-export-table-cell-width table-cell info) 0))
3345 (table-row (org-export-get-parent table-cell))
3346 (custom-style-prefix (org-odt-get-table-cell-styles
3347 table-cell info))
3348 (paragraph-style
3350 (and custom-style-prefix
3351 (format "%sTableParagraph" custom-style-prefix))
3352 (concat
3353 (cond
3354 ((and (= 1 (org-export-table-row-group table-row info))
3355 (org-export-table-has-header-p
3356 (org-export-get-parent-table table-row) info))
3357 "OrgTableHeading")
3358 ((let* ((table (org-export-get-parent-table table-cell))
3359 (table-attrs (org-export-read-attribute :attr_odt table))
3360 (table-header-columns
3361 (let ((cols (plist-get table-attrs :header-columns)))
3362 (and cols (read cols)))))
3363 (<= c (cond ((wholenump table-header-columns)
3364 (- table-header-columns 1))
3365 (table-header-columns 0)
3366 (t -1))))
3367 "OrgTableHeading")
3368 (t "OrgTableContents"))
3369 (capitalize (symbol-name (org-export-table-cell-alignment
3370 table-cell info))))))
3371 (cell-style-name
3373 (and custom-style-prefix (format "%sTableCell"
3374 custom-style-prefix))
3375 (concat
3376 "OrgTblCell"
3377 (when (or (org-export-table-row-starts-rowgroup-p table-row info)
3378 (zerop r)) "T")
3379 (when (org-export-table-row-ends-rowgroup-p table-row info) "B")
3380 (when (and (org-export-table-cell-starts-colgroup-p table-cell info)
3381 (not (zerop c)) ) "L"))))
3382 (cell-attributes
3383 (concat
3384 (format " table:style-name=\"%s\"" cell-style-name)
3385 (and (> horiz-span 0)
3386 (format " table:number-columns-spanned=\"%d\""
3387 (1+ horiz-span))))))
3388 (unless contents (setq contents ""))
3389 (concat
3390 (assert paragraph-style)
3391 (format "\n<table:table-cell%s>\n%s\n</table:table-cell>"
3392 cell-attributes
3393 (let ((table-cell-contents (org-element-contents table-cell)))
3394 (if (memq (org-element-type (car table-cell-contents))
3395 org-element-all-elements)
3396 contents
3397 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3398 paragraph-style contents))))
3399 (let (s)
3400 (dotimes (i horiz-span s)
3401 (setq s (concat s "\n<table:covered-table-cell/>"))))
3402 "\n")))
3405 ;;;; Table Row
3407 (defun org-odt-table-row (table-row contents info)
3408 "Transcode a TABLE-ROW element from Org to ODT.
3409 CONTENTS is the contents of the row. INFO is a plist used as a
3410 communication channel."
3411 ;; Rules are ignored since table separators are deduced from
3412 ;; borders of the current row.
3413 (when (eq (org-element-property :type table-row) 'standard)
3414 (let* ((rowgroup-tags
3415 (if (and (= 1 (org-export-table-row-group table-row info))
3416 (org-export-table-has-header-p
3417 (org-export-get-parent-table table-row) info))
3418 ;; If the row belongs to the first rowgroup and the
3419 ;; table has more than one row groups, then this row
3420 ;; belongs to the header row group.
3421 '("\n<table:table-header-rows>" . "\n</table:table-header-rows>")
3422 ;; Otherwise, it belongs to non-header row group.
3423 '("\n<table:table-rows>" . "\n</table:table-rows>"))))
3424 (concat
3425 ;; Does this row begin a rowgroup?
3426 (when (org-export-table-row-starts-rowgroup-p table-row info)
3427 (car rowgroup-tags))
3428 ;; Actual table row
3429 (format "\n<table:table-row>\n%s\n</table:table-row>" contents)
3430 ;; Does this row end a rowgroup?
3431 (when (org-export-table-row-ends-rowgroup-p table-row info)
3432 (cdr rowgroup-tags))))))
3435 ;;;; Table
3437 (defun org-odt-table-first-row-data-cells (table info)
3438 (let ((table-row
3439 (org-element-map table 'table-row
3440 (lambda (row)
3441 (unless (eq (org-element-property :type row) 'rule) row))
3442 info 'first-match))
3443 (special-column-p (org-export-table-has-special-column-p table)))
3444 (if (not special-column-p) (org-element-contents table-row)
3445 (cdr (org-element-contents table-row)))))
3447 (defun org-odt--table (table contents info)
3448 "Transcode a TABLE element from Org to ODT.
3449 CONTENTS is the contents of the table. INFO is a plist holding
3450 contextual information."
3451 (case (org-element-property :type table)
3452 ;; Case 1: table.el doesn't support export to OD format. Strip
3453 ;; such tables from export.
3454 (table.el
3455 (prog1 nil
3456 (message
3457 (concat
3458 "(ox-odt): Found table.el-type table in the source Org file."
3459 " table.el doesn't support export to ODT format."
3460 " Stripping the table from export."))))
3461 ;; Case 2: Native Org tables.
3462 (otherwise
3463 (let* ((captions (org-odt-format-label table info 'definition))
3464 (caption (car captions)) (short-caption (cdr captions))
3465 (attributes (org-export-read-attribute :attr_odt table))
3466 (custom-table-style (nth 1 (org-odt-table-style-spec table info)))
3467 (table-column-specs
3468 (function
3469 (lambda (table info)
3470 (let* ((table-style (or custom-table-style "OrgTable"))
3471 (column-style (format "%sColumn" table-style)))
3472 (mapconcat
3473 (lambda (table-cell)
3474 (let ((width (1+ (or (org-export-table-cell-width
3475 table-cell info) 0)))
3476 (s (format
3477 "\n<table:table-column table:style-name=\"%s\"/>"
3478 column-style))
3479 out)
3480 (dotimes (i width out) (setq out (concat s out)))))
3481 (org-odt-table-first-row-data-cells table info) "\n"))))))
3482 (concat
3483 ;; caption.
3484 (when caption
3485 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3486 "Table" caption))
3487 ;; begin table.
3488 (let* ((automatic-name
3489 (org-odt-add-automatic-style "Table" attributes)))
3490 (format
3491 "\n<table:table table:style-name=\"%s\"%s>"
3492 (or custom-table-style (cdr automatic-name) "OrgTable")
3493 (concat (when short-caption
3494 (format " table:name=\"%s\"" short-caption)))))
3495 ;; column specification.
3496 (funcall table-column-specs table info)
3497 ;; actual contents.
3498 "\n" contents
3499 ;; end table.
3500 "</table:table>")))))
3502 (defun org-odt-table (table contents info)
3503 "Transcode a TABLE element from Org to ODT.
3504 CONTENTS is the contents of the table. INFO is a plist holding
3505 contextual information.
3507 Use `org-odt--table' to typeset the table. Handle details
3508 pertaining to indentation here."
3509 (let* ((--element-preceded-by-table-p
3510 (function
3511 (lambda (element info)
3512 (loop for el in (org-export-get-previous-element element info t)
3513 thereis (eq (org-element-type el) 'table)))))
3514 (--walk-list-genealogy-and-collect-tags
3515 (function
3516 (lambda (table info)
3517 (let* ((genealogy (org-export-get-genealogy table))
3518 (list-genealogy
3519 (when (eq (org-element-type (car genealogy)) 'item)
3520 (loop for el in genealogy
3521 when (memq (org-element-type el)
3522 '(item plain-list))
3523 collect el)))
3524 (llh-genealogy
3525 (apply 'nconc
3526 (loop for el in genealogy
3527 when (and (eq (org-element-type el) 'headline)
3528 (org-export-low-level-p el info))
3529 collect
3530 (list el
3531 (assq 'headline
3532 (org-element-contents
3533 (org-export-get-parent el)))))))
3534 parent-list)
3535 (nconc
3536 ;; Handle list genealogy.
3537 (loop for el in list-genealogy collect
3538 (case (org-element-type el)
3539 (plain-list
3540 (setq parent-list el)
3541 (cons "</text:list>"
3542 (format "\n<text:list text:style-name=\"%s\" %s>"
3543 (case (org-element-property :type el)
3544 (ordered "OrgNumberedList")
3545 (unordered "OrgBulletedList")
3546 (descriptive-1 "OrgDescriptionList")
3547 (descriptive-2 "OrgDescriptionList"))
3548 "text:continue-numbering=\"true\"")))
3549 (item
3550 (cond
3551 ((not parent-list)
3552 (if (funcall --element-preceded-by-table-p table info)
3553 '("</text:list-header>" . "<text:list-header>")
3554 '("</text:list-item>" . "<text:list-header>")))
3555 ((funcall --element-preceded-by-table-p
3556 parent-list info)
3557 '("</text:list-header>" . "<text:list-header>"))
3558 (t '("</text:list-item>" . "<text:list-item>"))))))
3559 ;; Handle low-level headlines.
3560 (loop for el in llh-genealogy
3561 with step = 'item collect
3562 (case step
3563 (plain-list
3564 (setq step 'item) ; Flip-flop
3565 (setq parent-list el)
3566 (cons "</text:list>"
3567 (format "\n<text:list text:style-name=\"%s\" %s>"
3568 (if (org-export-numbered-headline-p
3569 el info)
3570 "OrgNumberedList"
3571 "OrgBulletedList")
3572 "text:continue-numbering=\"true\"")))
3573 (item
3574 (setq step 'plain-list) ; Flip-flop
3575 (cond
3576 ((not parent-list)
3577 (if (funcall --element-preceded-by-table-p table info)
3578 '("</text:list-header>" . "<text:list-header>")
3579 '("</text:list-item>" . "<text:list-header>")))
3580 ((let ((section? (org-export-get-previous-element
3581 parent-list info)))
3582 (and section?
3583 (eq (org-element-type section?) 'section)
3584 (assq 'table (org-element-contents section?))))
3585 '("</text:list-header>" . "<text:list-header>"))
3587 '("</text:list-item>" . "<text:list-item>")))))))))))
3588 (close-open-tags (funcall --walk-list-genealogy-and-collect-tags
3589 table info)))
3590 ;; OpenDocument schema does not permit table to occur within a
3591 ;; list item.
3593 ;; One solution - the easiest and lightweight, in terms of
3594 ;; implementation - is to put the table in an indented text box
3595 ;; and make the text box part of the list-item. Unfortunately if
3596 ;; the table is big and spans multiple pages, the text box could
3597 ;; overflow. In this case, the following attribute will come
3598 ;; handy.
3600 ;; ,---- From OpenDocument-v1.1.pdf
3601 ;; | 15.27.28 Overflow behavior
3602 ;; |
3603 ;; | For text boxes contained within text document, the
3604 ;; | style:overflow-behavior property specifies the behavior of text
3605 ;; | boxes where the containing text does not fit into the text
3606 ;; | box.
3607 ;; |
3608 ;; | If the attribute's value is clip, the text that does not fit
3609 ;; | into the text box is not displayed.
3610 ;; |
3611 ;; | If the attribute value is auto-create-new-frame, a new frame
3612 ;; | will be created on the next page, with the same position and
3613 ;; | dimensions of the original frame.
3614 ;; |
3615 ;; | If the style:overflow-behavior property's value is
3616 ;; | auto-create-new-frame and the text box has a minimum width or
3617 ;; | height specified, then the text box will grow until the page
3618 ;; | bounds are reached before a new frame is created.
3619 ;; `----
3621 ;; Unfortunately, LibreOffice-3.4.6 doesn't honor
3622 ;; auto-create-new-frame property and always resorts to clipping
3623 ;; the text box. This results in table being truncated.
3625 ;; So we solve the problem the hard (and fun) way using list
3626 ;; continuations.
3628 ;; The problem only becomes more interesting if you take in to
3629 ;; account the following facts:
3631 ;; - Description lists are simulated as plain lists.
3632 ;; - Low-level headlines can be listified.
3633 ;; - In Org-mode, a table can occur not only as a regular list
3634 ;; item, but also within description lists and low-level
3635 ;; headlines.
3637 ;; See `org-odt-translate-description-lists' and
3638 ;; `org-odt-translate-low-level-headlines' for how this is
3639 ;; tackled.
3641 (concat "\n"
3642 ;; Discontinue the list.
3643 (mapconcat 'car close-open-tags "\n")
3644 ;; Put the table in an indented section.
3645 (let* ((table (org-odt--table table contents info))
3646 (level (/ (length (mapcar 'car close-open-tags)) 2))
3647 (style (format "OrgIndentedSection-Level-%d" level)))
3648 (when table (org-odt-format-section table style)))
3649 ;; Continue the list.
3650 (mapconcat 'cdr (nreverse close-open-tags) "\n"))))
3653 ;;;; Target
3655 (defun org-odt-target (target contents info)
3656 "Transcode a TARGET object from Org to ODT.
3657 CONTENTS is nil. INFO is a plist holding contextual
3658 information."
3659 (let ((value (org-element-property :value target)))
3660 (org-odt--target "" (org-export-solidify-link-text value))))
3663 ;;;; Timestamp
3665 (defun org-odt-timestamp (timestamp contents info)
3666 "Transcode a TIMESTAMP object from Org to ODT.
3667 CONTENTS is nil. INFO is a plist used as a communication
3668 channel."
3669 (let* ((raw-value (org-element-property :raw-value timestamp))
3670 (type (org-element-property :type timestamp)))
3671 (if (not org-odt-use-date-fields)
3672 (let ((value (org-odt-plain-text
3673 (org-timestamp-translate timestamp) info)))
3674 (case (org-element-property :type timestamp)
3675 ((active active-range)
3676 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3677 "OrgActiveTimestamp" value))
3678 ((inactive inactive-range)
3679 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3680 "OrgInactiveTimestamp" value))
3681 (otherwise value)))
3682 (case type
3683 (active
3684 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3685 "OrgActiveTimestamp"
3686 (format "&lt;%s&gt;" (org-odt--format-timestamp timestamp))))
3687 (inactive
3688 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3689 "OrgInactiveTimestamp"
3690 (format "[%s]" (org-odt--format-timestamp timestamp))))
3691 (active-range
3692 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3693 "OrgActiveTimestamp"
3694 (format "&lt;%s&gt;&#x2013;&lt;%s&gt;"
3695 (org-odt--format-timestamp timestamp)
3696 (org-odt--format-timestamp timestamp 'end))))
3697 (inactive-range
3698 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3699 "OrgInactiveTimestamp"
3700 (format "[%s]&#x2013;[%s]"
3701 (org-odt--format-timestamp timestamp)
3702 (org-odt--format-timestamp timestamp 'end))))
3703 (otherwise
3704 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3705 "OrgDiaryTimestamp"
3706 (org-odt-plain-text (org-timestamp-translate timestamp)
3707 info)))))))
3710 ;;;; Underline
3712 (defun org-odt-underline (underline contents info)
3713 "Transcode UNDERLINE from Org to ODT.
3714 CONTENTS is the text with underline markup. INFO is a plist
3715 holding contextual information."
3716 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3717 "Underline" contents))
3720 ;;;; Verbatim
3722 (defun org-odt-verbatim (verbatim contents info)
3723 "Transcode a VERBATIM object from Org to ODT.
3724 CONTENTS is nil. INFO is a plist used as a communication
3725 channel."
3726 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3727 "OrgCode" (org-odt--encode-plain-text
3728 (org-element-property :value verbatim))))
3731 ;;;; Verse Block
3733 (defun org-odt-verse-block (verse-block contents info)
3734 "Transcode a VERSE-BLOCK element from Org to ODT.
3735 CONTENTS is verse block contents. INFO is a plist holding
3736 contextual information."
3737 ;; Add line breaks to each line of verse.
3738 (setq contents (replace-regexp-in-string
3739 "\\(<text:line-break/>\\)?[ \t]*\n"
3740 "<text:line-break/>" contents))
3741 ;; Replace tabs and spaces.
3742 (setq contents (org-odt--encode-tabs-and-spaces contents))
3743 ;; Surround it in a verse environment.
3744 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3745 "OrgVerse" contents))
3749 ;;; Filters
3751 ;;;; LaTeX fragments
3753 (defun org-odt--translate-latex-fragments (tree backend info)
3754 (let ((processing-type (plist-get info :with-latex))
3755 (count 0))
3756 ;; Normalize processing-type to one of dvipng, mathml or verbatim.
3757 ;; If the desired converter is not available, force verbatim
3758 ;; processing.
3759 (case processing-type
3760 ((t mathml)
3761 (if (and (fboundp 'org-format-latex-mathml-available-p)
3762 (org-format-latex-mathml-available-p))
3763 (setq processing-type 'mathml)
3764 (message "LaTeX to MathML converter not available.")
3765 (setq processing-type 'verbatim)))
3766 (dvipng
3767 (unless (and (org-check-external-command "latex" "" t)
3768 (org-check-external-command "dvipng" "" t))
3769 (message "LaTeX to PNG converter not available.")
3770 (setq processing-type 'verbatim)))
3771 (otherwise
3772 (message "Unknown LaTeX option. Forcing verbatim.")
3773 (setq processing-type 'verbatim)))
3775 ;; Store normalized value for later use.
3776 (when (plist-get info :with-latex)
3777 (plist-put info :with-latex processing-type))
3778 (message "Formatting LaTeX using %s" processing-type)
3780 ;; Convert `latex-fragment's and `latex-environment's.
3781 (when (memq processing-type '(mathml dvipng))
3782 (org-element-map tree '(latex-fragment latex-environment)
3783 (lambda (latex-*)
3784 (incf count)
3785 (let* ((latex-frag (org-element-property :value latex-*))
3786 (input-file (plist-get info :input-file))
3787 (cache-dir (file-name-directory input-file))
3788 (cache-subdir (concat
3789 (case processing-type
3790 (dvipng "ltxpng/")
3791 (mathml "ltxmathml/"))
3792 (file-name-sans-extension
3793 (file-name-nondirectory input-file))))
3794 (display-msg
3795 (case processing-type
3796 (dvipng (format "Creating LaTeX Image %d..." count))
3797 (mathml (format "Creating MathML snippet %d..." count))))
3798 ;; Get an Org-style link to PNG image or the MathML
3799 ;; file.
3800 (org-link
3801 (let ((link (with-temp-buffer
3802 (insert latex-frag)
3803 (org-format-latex cache-subdir cache-dir
3804 nil display-msg
3805 nil nil processing-type)
3806 (buffer-substring-no-properties
3807 (point-min) (point-max)))))
3808 (if (not (string-match "file:\\([^]]*\\)" link))
3809 (prog1 nil (message "LaTeX Conversion failed."))
3810 link))))
3811 (when org-link
3812 ;; Conversion succeeded. Parse above Org-style link to a
3813 ;; `link' object.
3814 (let* ((link (car (org-element-map (with-temp-buffer
3815 (org-mode)
3816 (insert org-link)
3817 (org-element-parse-buffer))
3818 'link 'identity))))
3819 ;; Orphan the link.
3820 (org-element-put-property link :parent nil)
3821 (let* (
3822 (replacement
3823 (case (org-element-type latex-*)
3824 ;; Case 1: LaTeX environment.
3825 ;; Mimic a "standalone image or formula" by
3826 ;; enclosing the `link' in a `paragraph'.
3827 ;; Copy over original attributes, captions to
3828 ;; the enclosing paragraph.
3829 (latex-environment
3830 (org-element-adopt-elements
3831 (list 'paragraph
3832 (list :style "OrgFormula"
3833 :name (org-element-property :name
3834 latex-*)
3835 :caption (org-element-property :caption
3836 latex-*)))
3837 link))
3838 ;; Case 2: LaTeX fragment.
3839 ;; No special action.
3840 (latex-fragment link))))
3841 ;; Note down the object that link replaces.
3842 (org-element-put-property replacement :replaces
3843 (list (org-element-type latex-*)
3844 (list :value latex-frag)))
3845 ;; Replace now.
3846 (org-element-set-element latex-* replacement))))))
3847 info)))
3848 tree)
3851 ;;;; Description lists
3853 ;; This translator is necessary to handle indented tables in a uniform
3854 ;; manner. See comment in `org-odt--table'.
3856 (defun org-odt--translate-description-lists (tree backend info)
3857 ;; OpenDocument has no notion of a description list. So simulate it
3858 ;; using plain lists. Description lists in the exported document
3859 ;; are typeset in the same manner as they are in a typical HTML
3860 ;; document.
3862 ;; Specifically, a description list like this:
3864 ;; ,----
3865 ;; | - term-1 :: definition-1
3866 ;; | - term-2 :: definition-2
3867 ;; `----
3869 ;; gets translated in to the following form:
3871 ;; ,----
3872 ;; | - term-1
3873 ;; | - definition-1
3874 ;; | - term-2
3875 ;; | - definition-2
3876 ;; `----
3878 ;; Further effect is achieved by fixing the OD styles as below:
3880 ;; 1. Set the :type property of the simulated lists to
3881 ;; `descriptive-1' and `descriptive-2'. Map these to list-styles
3882 ;; that has *no* bullets whatsoever.
3884 ;; 2. The paragraph containing the definition term is styled to be
3885 ;; in bold.
3887 (org-element-map tree 'plain-list
3888 (lambda (el)
3889 (when (equal (org-element-property :type el) 'descriptive)
3890 (org-element-set-element
3892 (apply 'org-element-adopt-elements
3893 (list 'plain-list (list :type 'descriptive-1))
3894 (mapcar
3895 (lambda (item)
3896 (org-element-adopt-elements
3897 (list 'item (list :checkbox (org-element-property
3898 :checkbox item)))
3899 (list 'paragraph (list :style "Text_20_body_20_bold")
3900 (or (org-element-property :tag item) "(no term)"))
3901 (org-element-adopt-elements
3902 (list 'plain-list (list :type 'descriptive-2))
3903 (apply 'org-element-adopt-elements
3904 (list 'item nil)
3905 (org-element-contents item)))))
3906 (org-element-contents el)))))
3907 nil)
3908 info)
3909 tree)
3911 ;;;; List tables
3913 ;; Lists that are marked with attribute `:list-table' are called as
3914 ;; list tables. They will be rendered as a table within the exported
3915 ;; document.
3917 ;; Consider an example. The following list table
3919 ;; #+attr_odt :list-table t
3920 ;; - Row 1
3921 ;; - 1.1
3922 ;; - 1.2
3923 ;; - 1.3
3924 ;; - Row 2
3925 ;; - 2.1
3926 ;; - 2.2
3927 ;; - 2.3
3929 ;; will be exported as though it were an Org table like the one show
3930 ;; below.
3932 ;; | Row 1 | 1.1 | 1.2 | 1.3 |
3933 ;; | Row 2 | 2.1 | 2.2 | 2.3 |
3935 ;; Note that org-tables are NOT multi-line and each line is mapped to
3936 ;; a unique row in the exported document. So if an exported table
3937 ;; needs to contain a single paragraph (with copious text) it needs to
3938 ;; be typed up in a single line. Editing such long lines using the
3939 ;; table editor will be a cumbersome task. Furthermore inclusion of
3940 ;; multi-paragraph text in a table cell is well-nigh impossible.
3942 ;; A LIST-TABLE circumvents above problems.
3944 ;; Note that in the example above the list items could be paragraphs
3945 ;; themselves and the list can be arbitrarily deep.
3947 ;; Inspired by following thread:
3948 ;; https://lists.gnu.org/archive/html/emacs-orgmode/2011-03/msg01101.html
3950 ;; Translate lists to tables
3952 (defun org-odt--translate-list-tables (tree backend info)
3953 (org-element-map tree 'plain-list
3954 (lambda (l1-list)
3955 (when (org-export-read-attribute :attr_odt l1-list :list-table)
3956 ;; Replace list with table.
3957 (org-element-set-element
3958 l1-list
3959 ;; Build replacement table.
3960 (apply 'org-element-adopt-elements
3961 (list 'table '(:type org :attr_odt (":style \"GriddedTable\"")))
3962 (org-element-map l1-list 'item
3963 (lambda (l1-item)
3964 (let* ((l1-item-contents (org-element-contents l1-item))
3965 l1-item-leading-text l2-list)
3966 ;; Remove Level-2 list from the Level-item. It
3967 ;; will be subsequently attached as table-cells.
3968 (let ((cur l1-item-contents) prev)
3969 (while (and cur (not (eq (org-element-type (car cur))
3970 'plain-list)))
3971 (setq prev cur)
3972 (setq cur (cdr cur)))
3973 (when prev
3974 (setcdr prev nil)
3975 (setq l2-list (car cur)))
3976 (setq l1-item-leading-text l1-item-contents))
3977 ;; Level-1 items start a table row.
3978 (apply 'org-element-adopt-elements
3979 (list 'table-row (list :type 'standard))
3980 ;; Leading text of level-1 item define
3981 ;; the first table-cell.
3982 (apply 'org-element-adopt-elements
3983 (list 'table-cell nil)
3984 l1-item-leading-text)
3985 ;; Level-2 items define subsequent
3986 ;; table-cells of the row.
3987 (org-element-map l2-list 'item
3988 (lambda (l2-item)
3989 (apply 'org-element-adopt-elements
3990 (list 'table-cell nil)
3991 (org-element-contents l2-item)))
3992 info nil 'item))))
3993 info nil 'item))))
3994 nil)
3995 info)
3996 tree)
3999 ;;; Interactive functions
4001 (defun org-odt-create-manifest-file-entry (&rest args)
4002 (push args org-odt-manifest-file-entries))
4004 (defun org-odt-write-manifest-file ()
4005 (make-directory (concat org-odt-zip-dir "META-INF"))
4006 (let ((manifest-file (concat org-odt-zip-dir "META-INF/manifest.xml")))
4007 (with-current-buffer
4008 (let ((nxml-auto-insert-xml-declaration-flag nil))
4009 (find-file-noselect manifest-file t))
4010 (insert
4011 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
4012 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
4013 (mapc
4014 (lambda (file-entry)
4015 (let* ((version (nth 2 file-entry))
4016 (extra (if (not version) ""
4017 (format " manifest:version=\"%s\"" version))))
4018 (insert
4019 (format org-odt-manifest-file-entry-tag
4020 (nth 0 file-entry) (nth 1 file-entry) extra))))
4021 org-odt-manifest-file-entries)
4022 (insert "\n</manifest:manifest>"))))
4024 (defmacro org-odt--export-wrap (out-file &rest body)
4025 `(let* ((--out-file ,out-file)
4026 (out-file-type (file-name-extension --out-file))
4027 (org-odt-xml-files '("META-INF/manifest.xml" "content.xml"
4028 "meta.xml" "styles.xml"))
4029 ;; Initialize temporary workarea. All files that end up in
4030 ;; the exported document get parked/created here.
4031 (org-odt-zip-dir (file-name-as-directory
4032 (make-temp-file (format "%s-" out-file-type) t)))
4033 (org-odt-manifest-file-entries nil)
4034 (--cleanup-xml-buffers
4035 (function
4036 (lambda nil
4037 ;; Kill all XML buffers.
4038 (mapc (lambda (file)
4039 (let ((buf (find-buffer-visiting
4040 (concat org-odt-zip-dir file))))
4041 (when buf
4042 (with-current-buffer buf
4043 (set-buffer-modified-p nil)
4044 (kill-buffer buf)))))
4045 org-odt-xml-files)
4046 ;; Delete temporary directory and also other embedded
4047 ;; files that get copied there.
4048 (delete-directory org-odt-zip-dir t)))))
4049 (condition-case err
4050 (progn
4051 (unless (executable-find "zip")
4052 ;; Not at all OSes ship with zip by default
4053 (error "Executable \"zip\" needed for creating OpenDocument files"))
4054 ;; Do export. This creates a bunch of xml files ready to be
4055 ;; saved and zipped.
4056 (progn ,@body)
4057 ;; Create a manifest entry for content.xml.
4058 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
4059 ;; Write mimetype file
4060 (let* ((mimetypes
4061 '(("odt" . "application/vnd.oasis.opendocument.text")
4062 ("odf" . "application/vnd.oasis.opendocument.formula")))
4063 (mimetype (cdr (assoc-string out-file-type mimetypes t))))
4064 (unless mimetype
4065 (error "Unknown OpenDocument backend %S" out-file-type))
4066 (write-region mimetype nil (concat org-odt-zip-dir "mimetype"))
4067 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
4068 ;; Write out the manifest entries before zipping
4069 (org-odt-write-manifest-file)
4070 ;; Save all XML files.
4071 (mapc (lambda (file)
4072 (let ((buf (find-buffer-visiting
4073 (concat org-odt-zip-dir file))))
4074 (when buf
4075 (with-current-buffer buf
4076 ;; Prettify output if needed.
4077 (when org-odt-prettify-xml
4078 (indent-region (point-min) (point-max)))
4079 (save-buffer 0)))))
4080 org-odt-xml-files)
4081 ;; Run zip.
4082 (let* ((target --out-file)
4083 (target-name (file-name-nondirectory target))
4084 (cmds `(("zip" "-mX0" ,target-name "mimetype")
4085 ("zip" "-rmTq" ,target-name "."))))
4086 ;; If a file with same name as the desired output file
4087 ;; exists, remove it.
4088 (when (file-exists-p target)
4089 (delete-file target))
4090 ;; Zip up the xml files.
4091 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
4092 (message "Creating ODT file...")
4093 ;; Switch temporarily to content.xml. This way Zip
4094 ;; process will inherit `org-odt-zip-dir' as the current
4095 ;; directory.
4096 (with-current-buffer
4097 (find-file-noselect (concat org-odt-zip-dir "content.xml") t)
4098 (mapc
4099 (lambda (cmd)
4100 (message "Running %s" (mapconcat 'identity cmd " "))
4101 (setq err-string
4102 (with-output-to-string
4103 (setq exitcode
4104 (apply 'call-process (car cmd)
4105 nil standard-output nil (cdr cmd)))))
4106 (or (zerop exitcode)
4107 (error (concat "Unable to create OpenDocument file."
4108 (format " Zip failed with error (%s)"
4109 err-string)))))
4110 cmds)))
4111 ;; Move the zip file from temporary work directory to
4112 ;; user-mandated location.
4113 (rename-file (concat org-odt-zip-dir target-name) target)
4114 (message "Created %s" (expand-file-name target))
4115 ;; Cleanup work directory and work files.
4116 (funcall --cleanup-xml-buffers)
4117 ;; Open the OpenDocument file in archive-mode for
4118 ;; examination.
4119 (find-file-noselect target t)
4120 ;; Return exported file.
4121 (cond
4122 ;; Case 1: Conversion desired on exported file. Run the
4123 ;; converter on the OpenDocument file. Return the
4124 ;; converted file.
4125 (org-odt-preferred-output-format
4126 (or (org-odt-convert target org-odt-preferred-output-format)
4127 target))
4128 ;; Case 2: No further conversion. Return exported
4129 ;; OpenDocument file.
4130 (t target))))
4131 (error
4132 ;; Cleanup work directory and work files.
4133 (funcall --cleanup-xml-buffers)
4134 (message "OpenDocument export failed: %s"
4135 (error-message-string err))))))
4138 ;;;; Export to OpenDocument formula
4140 ;;;###autoload
4141 (defun org-odt-export-as-odf (latex-frag &optional odf-file)
4142 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
4143 Use `org-create-math-formula' to convert LATEX-FRAG first to
4144 MathML. When invoked as an interactive command, use
4145 `org-latex-regexps' to infer LATEX-FRAG from currently active
4146 region. If no LaTeX fragments are found, prompt for it. Push
4147 MathML source to kill ring depending on the value of
4148 `org-export-copy-to-kill-ring'."
4149 (interactive
4150 `(,(let (frag)
4151 (setq frag (and (setq frag (and (region-active-p)
4152 (buffer-substring (region-beginning)
4153 (region-end))))
4154 (loop for e in org-latex-regexps
4155 thereis (when (string-match (nth 1 e) frag)
4156 (match-string (nth 2 e) frag)))))
4157 (read-string "LaTeX Fragment: " frag nil frag))
4158 ,(let ((odf-filename (expand-file-name
4159 (concat
4160 (file-name-sans-extension
4161 (or (file-name-nondirectory buffer-file-name)))
4162 "." "odf")
4163 (file-name-directory buffer-file-name))))
4164 (read-file-name "ODF filename: " nil odf-filename nil
4165 (file-name-nondirectory odf-filename)))))
4166 (let ((filename (or odf-file
4167 (expand-file-name
4168 (concat
4169 (file-name-sans-extension
4170 (or (file-name-nondirectory buffer-file-name)))
4171 "." "odf")
4172 (file-name-directory buffer-file-name)))))
4173 (org-odt--export-wrap
4174 filename
4175 (let* ((buffer (progn
4176 (require 'nxml-mode)
4177 (let ((nxml-auto-insert-xml-declaration-flag nil))
4178 (find-file-noselect (concat org-odt-zip-dir
4179 "content.xml") t))))
4180 (coding-system-for-write 'utf-8)
4181 (save-buffer-coding-system 'utf-8))
4182 (set-buffer buffer)
4183 (set-buffer-file-coding-system coding-system-for-write)
4184 (let ((mathml (org-create-math-formula latex-frag)))
4185 (unless mathml (error "No Math formula created"))
4186 (insert mathml)
4187 ;; Add MathML to kill ring, if needed.
4188 (when (org-export--copy-to-kill-ring-p)
4189 (org-kill-new (buffer-string))))))))
4191 ;;;###autoload
4192 (defun org-odt-export-as-odf-and-open ()
4193 "Export LaTeX fragment as OpenDocument formula and immediately open it.
4194 Use `org-odt-export-as-odf' to read LaTeX fragment and OpenDocument
4195 formula file."
4196 (interactive)
4197 (org-open-file (call-interactively 'org-odt-export-as-odf) 'system))
4200 ;;;; Export to OpenDocument Text
4202 ;;;###autoload
4203 (defun org-odt-export-to-odt (&optional async subtreep visible-only ext-plist)
4204 "Export current buffer to a ODT file.
4206 If narrowing is active in the current buffer, only export its
4207 narrowed part.
4209 If a region is active, export that region.
4211 A non-nil optional argument ASYNC means the process should happen
4212 asynchronously. The resulting file should be accessible through
4213 the `org-export-stack' interface.
4215 When optional argument SUBTREEP is non-nil, export the sub-tree
4216 at point, extracting information from the headline properties
4217 first.
4219 When optional argument VISIBLE-ONLY is non-nil, don't export
4220 contents of hidden elements.
4222 EXT-PLIST, when provided, is a property list with external
4223 parameters overriding Org default settings, but still inferior to
4224 file-local settings.
4226 Return output file's name."
4227 (interactive)
4228 (let ((outfile (org-export-output-file-name ".odt" subtreep)))
4229 (if async
4230 (org-export-async-start (lambda (f) (org-export-add-to-stack f 'odt))
4231 `(expand-file-name
4232 (org-odt--export-wrap
4233 ,outfile
4234 (let* ((org-odt-embedded-images-count 0)
4235 (org-odt-embedded-formulas-count 0)
4236 (org-odt-automatic-styles nil)
4237 (org-odt-object-counters nil)
4238 ;; Let `htmlfontify' know that we are interested in
4239 ;; collecting styles.
4240 (hfy-user-sheet-assoc nil))
4241 ;; Initialize content.xml and kick-off the export
4242 ;; process.
4243 (let ((out-buf
4244 (progn
4245 (require 'nxml-mode)
4246 (let ((nxml-auto-insert-xml-declaration-flag nil))
4247 (find-file-noselect
4248 (concat org-odt-zip-dir "content.xml") t)))))
4249 (org-export-to-buffer
4250 'odt out-buf ,subtreep ,visible-only nil ',ext-plist))))))
4251 (org-odt--export-wrap
4252 outfile
4253 (let* ((org-odt-embedded-images-count 0)
4254 (org-odt-embedded-formulas-count 0)
4255 (org-odt-automatic-styles nil)
4256 (org-odt-object-counters nil)
4257 ;; Let `htmlfontify' know that we are interested in collecting
4258 ;; styles.
4259 (hfy-user-sheet-assoc nil))
4260 ;; Initialize content.xml and kick-off the export process.
4261 (let ((out-buf (progn
4262 (require 'nxml-mode)
4263 (let ((nxml-auto-insert-xml-declaration-flag nil))
4264 (find-file-noselect
4265 (concat org-odt-zip-dir "content.xml") t)))))
4266 (org-export-to-buffer
4267 'odt out-buf subtreep visible-only nil ext-plist)))))))
4270 ;;;; Convert between OpenDocument and other formats
4272 (defun org-odt-reachable-p (in-fmt out-fmt)
4273 "Return non-nil if IN-FMT can be converted to OUT-FMT."
4274 (catch 'done
4275 (let ((reachable-formats (org-odt-do-reachable-formats in-fmt)))
4276 (dolist (e reachable-formats)
4277 (let ((out-fmt-spec (assoc out-fmt (cdr e))))
4278 (when out-fmt-spec
4279 (throw 'done (cons (car e) out-fmt-spec))))))))
4281 (defun org-odt-do-convert (in-file out-fmt &optional prefix-arg)
4282 "Workhorse routine for `org-odt-convert'."
4283 (require 'browse-url)
4284 (let* ((in-file (expand-file-name (or in-file buffer-file-name)))
4285 (dummy (or (file-readable-p in-file)
4286 (error "Cannot read %s" in-file)))
4287 (in-fmt (file-name-extension in-file))
4288 (out-fmt (or out-fmt (error "Output format unspecified")))
4289 (how (or (org-odt-reachable-p in-fmt out-fmt)
4290 (error "Cannot convert from %s format to %s format?"
4291 in-fmt out-fmt)))
4292 (convert-process (car how))
4293 (out-file (concat (file-name-sans-extension in-file) "."
4294 (nth 1 (or (cdr how) out-fmt))))
4295 (extra-options (or (nth 2 (cdr how)) ""))
4296 (out-dir (file-name-directory in-file))
4297 (cmd (format-spec convert-process
4298 `((?i . ,(shell-quote-argument in-file))
4299 (?I . ,(browse-url-file-url in-file))
4300 (?f . ,out-fmt)
4301 (?o . ,out-file)
4302 (?O . ,(browse-url-file-url out-file))
4303 (?d . , (shell-quote-argument out-dir))
4304 (?D . ,(browse-url-file-url out-dir))
4305 (?x . ,extra-options)))))
4306 (when (file-exists-p out-file)
4307 (delete-file out-file))
4309 (message "Executing %s" cmd)
4310 (let ((cmd-output (shell-command-to-string cmd)))
4311 (message "%s" cmd-output))
4313 (cond
4314 ((file-exists-p out-file)
4315 (message "Exported to %s" out-file)
4316 (when prefix-arg
4317 (message "Opening %s..." out-file)
4318 (org-open-file out-file 'system))
4319 out-file)
4321 (message "Export to %s failed" out-file)
4322 nil))))
4324 (defun org-odt-do-reachable-formats (in-fmt)
4325 "Return verbose info about formats to which IN-FMT can be converted.
4326 Return a list where each element is of the
4327 form (CONVERTER-PROCESS . OUTPUT-FMT-ALIST). See
4328 `org-odt-convert-processes' for CONVERTER-PROCESS and see
4329 `org-odt-convert-capabilities' for OUTPUT-FMT-ALIST."
4330 (let* ((converter
4331 (and org-odt-convert-process
4332 (cadr (assoc-string org-odt-convert-process
4333 org-odt-convert-processes t))))
4334 (capabilities
4335 (and org-odt-convert-process
4336 (cadr (assoc-string org-odt-convert-process
4337 org-odt-convert-processes t))
4338 org-odt-convert-capabilities))
4339 reachable-formats)
4340 (when converter
4341 (dolist (c capabilities)
4342 (when (member in-fmt (nth 1 c))
4343 (push (cons converter (nth 2 c)) reachable-formats))))
4344 reachable-formats))
4346 (defun org-odt-reachable-formats (in-fmt)
4347 "Return list of formats to which IN-FMT can be converted.
4348 The list of the form (OUTPUT-FMT-1 OUTPUT-FMT-2 ...)."
4349 (let (l)
4350 (mapc (lambda (e) (add-to-list 'l e))
4351 (apply 'append (mapcar
4352 (lambda (e) (mapcar 'car (cdr e)))
4353 (org-odt-do-reachable-formats in-fmt))))
4356 (defun org-odt-convert-read-params ()
4357 "Return IN-FILE and OUT-FMT params for `org-odt-do-convert'.
4358 This is a helper routine for interactive use."
4359 (let* ((input (if (featurep 'ido) 'ido-completing-read 'completing-read))
4360 (in-file (read-file-name "File to be converted: "
4361 nil buffer-file-name t))
4362 (in-fmt (file-name-extension in-file))
4363 (out-fmt-choices (org-odt-reachable-formats in-fmt))
4364 (out-fmt
4365 (or (and out-fmt-choices
4366 (funcall input "Output format: "
4367 out-fmt-choices nil nil nil))
4368 (error
4369 "No known converter or no known output formats for %s files"
4370 in-fmt))))
4371 (list in-file out-fmt)))
4373 ;;;###autoload
4374 (defun org-odt-convert (&optional in-file out-fmt prefix-arg)
4375 "Convert IN-FILE to format OUT-FMT using a command line converter.
4376 IN-FILE is the file to be converted. If unspecified, it defaults
4377 to variable `buffer-file-name'. OUT-FMT is the desired output
4378 format. Use `org-odt-convert-process' as the converter.
4379 If PREFIX-ARG is non-nil then the newly converted file is opened
4380 using `org-open-file'."
4381 (interactive
4382 (append (org-odt-convert-read-params) current-prefix-arg))
4383 (org-odt-do-convert in-file out-fmt prefix-arg))
4385 ;;; Library Initializations
4387 (mapc
4388 (lambda (desc)
4389 ;; Let Emacs open all OpenDocument files in archive mode
4390 (add-to-list 'auto-mode-alist
4391 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
4392 org-odt-file-extensions)
4394 (provide 'ox-odt)
4396 ;; Local variables:
4397 ;; generated-autoload-file: "org-loaddefs.el"
4398 ;; End:
4400 ;;; ox-odt.el ends here