org.el: Update `customize-package-emacs-version-alist' and fix :version/:package...
[org-mode.git] / lisp / ox-odt.el
bloba1caff78b09e42456a5e12d31a2ac383df0467b8
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-element-property :value code)))
1625 ;;;; Comment
1627 ;; Comments are ignored.
1630 ;;;; Comment Block
1632 ;; Comment Blocks are ignored.
1635 ;;;; Drawer
1637 (defun org-odt-drawer (drawer contents info)
1638 "Transcode a DRAWER element from Org to ODT.
1639 CONTENTS holds the contents of the block. INFO is a plist
1640 holding contextual information."
1641 (let* ((name (org-element-property :drawer-name drawer))
1642 (output (if (functionp org-odt-format-drawer-function)
1643 (funcall org-odt-format-drawer-function
1644 name contents)
1645 ;; If there's no user defined function: simply
1646 ;; display contents of the drawer.
1647 contents)))
1648 output))
1651 ;;;; Dynamic Block
1653 (defun org-odt-dynamic-block (dynamic-block contents info)
1654 "Transcode a DYNAMIC-BLOCK element from Org to ODT.
1655 CONTENTS holds the contents of the block. INFO is a plist
1656 holding contextual information. See `org-export-data'."
1657 contents)
1660 ;;;; Entity
1662 (defun org-odt-entity (entity contents info)
1663 "Transcode an ENTITY object from Org to ODT.
1664 CONTENTS are the definition itself. INFO is a plist holding
1665 contextual information."
1666 (org-element-property :utf-8 entity))
1669 ;;;; Example Block
1671 (defun org-odt-example-block (example-block contents info)
1672 "Transcode a EXAMPLE-BLOCK element from Org to ODT.
1673 CONTENTS is nil. INFO is a plist holding contextual information."
1674 (org-odt-format-code example-block info))
1677 ;;;; Export Snippet
1679 (defun org-odt-export-snippet (export-snippet contents info)
1680 "Transcode a EXPORT-SNIPPET object from Org to ODT.
1681 CONTENTS is nil. INFO is a plist holding contextual information."
1682 (when (eq (org-export-snippet-backend export-snippet) 'odt)
1683 (org-element-property :value export-snippet)))
1686 ;;;; Export Block
1688 (defun org-odt-export-block (export-block contents info)
1689 "Transcode a EXPORT-BLOCK element from Org to ODT.
1690 CONTENTS is nil. INFO is a plist holding contextual information."
1691 (when (string= (org-element-property :type export-block) "ODT")
1692 (org-remove-indentation (org-element-property :value export-block))))
1695 ;;;; Fixed Width
1697 (defun org-odt-fixed-width (fixed-width contents info)
1698 "Transcode a FIXED-WIDTH element from Org to ODT.
1699 CONTENTS is nil. INFO is a plist holding contextual information."
1700 (org-odt-do-format-code (org-element-property :value fixed-width)))
1703 ;;;; Footnote Definition
1705 ;; Footnote Definitions are ignored.
1708 ;;;; Footnote Reference
1710 (defun org-odt-footnote-reference (footnote-reference contents info)
1711 "Transcode a FOOTNOTE-REFERENCE element from Org to ODT.
1712 CONTENTS is nil. INFO is a plist holding contextual information."
1713 (let ((--format-footnote-definition
1714 (function
1715 (lambda (n def)
1716 (setq n (format "%d" n))
1717 (let ((id (concat "fn" n))
1718 (note-class "footnote")
1719 (par-style "Footnote"))
1720 (format
1721 "<text:note text:id=\"%s\" text:note-class=\"%s\">%s</text:note>"
1722 id note-class
1723 (concat
1724 (format "<text:note-citation>%s</text:note-citation>" n)
1725 (format "<text:note-body>%s</text:note-body>" def)))))))
1726 (--format-footnote-reference
1727 (function
1728 (lambda (n)
1729 (setq n (format "%d" n))
1730 (let ((note-class "footnote")
1731 (ref-format "text")
1732 (ref-name (concat "fn" n)))
1733 (format
1734 "<text:span text:style-name=\"%s\">%s</text:span>"
1735 "OrgSuperscript"
1736 (format "<text:note-ref text:note-class=\"%s\" text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:note-ref>"
1737 note-class ref-format ref-name n)))))))
1738 (concat
1739 ;; Insert separator between two footnotes in a row.
1740 (let ((prev (org-export-get-previous-element footnote-reference info)))
1741 (and (eq (org-element-type prev) 'footnote-reference)
1742 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1743 "OrgSuperscript" ",")))
1744 ;; Trancode footnote reference.
1745 (let ((n (org-export-get-footnote-number footnote-reference info)))
1746 (cond
1747 ((not (org-export-footnote-first-reference-p footnote-reference info))
1748 (funcall --format-footnote-reference n))
1749 ;; Inline definitions are secondary strings.
1750 ;; Non-inline footnotes definitions are full Org data.
1752 (let* ((raw (org-export-get-footnote-definition footnote-reference
1753 info))
1754 (def (let ((def (org-trim (org-export-data raw info))))
1755 (if (eq (org-element-type raw) 'org-data) def
1756 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1757 "Footnote" def)))))
1758 (funcall --format-footnote-definition n def))))))))
1761 ;;;; Headline
1763 (defun* org-odt-format-headline
1764 (todo todo-type priority text tags
1765 &key level section-number headline-label &allow-other-keys)
1766 (concat
1767 ;; Todo.
1768 (when todo
1769 (let ((style (if (member todo org-done-keywords) "OrgDone" "OrgTodo")))
1770 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1771 style todo)))
1772 (when priority
1773 (let* ((style (format "OrgPriority-%s" priority))
1774 (priority (format "[#%c]" priority)))
1775 (format "<text:span text:style-name=\"%s\">%s</text:span> "
1776 style priority)))
1777 ;; Title.
1778 text
1779 ;; Tags.
1780 (when tags
1781 (concat
1782 "<text:tab/>"
1783 (format "<text:span text:style-name=\"%s\">[%s]</text:span>"
1784 "OrgTags" (mapconcat
1785 (lambda (tag)
1786 (format
1787 "<text:span text:style-name=\"%s\">%s</text:span>"
1788 "OrgTag" tag)) tags " : "))))))
1790 (defun org-odt-format-headline--wrap (headline translations info
1791 &optional format-function
1792 &rest extra-keys)
1793 "Transcode a HEADLINE element from Org to ODT.
1794 CONTENTS holds the contents of the headline. INFO is a plist
1795 holding contextual information."
1796 (setq translations (or translations (plist-get info :translate-alist)))
1797 (let* ((level (+ (org-export-get-relative-level headline info)))
1798 (headline-number (org-export-get-headline-number headline info))
1799 (section-number (and (org-export-numbered-headline-p headline info)
1800 (mapconcat 'number-to-string
1801 headline-number ".")))
1802 (todo (and (plist-get info :with-todo-keywords)
1803 (let ((todo (org-element-property :todo-keyword headline)))
1804 (and todo (org-export-data-with-translations
1805 todo translations info)))))
1806 (todo-type (and todo (org-element-property :todo-type headline)))
1807 (priority (and (plist-get info :with-priority)
1808 (org-element-property :priority headline)))
1809 (text (org-export-data-with-translations
1810 (org-element-property :title headline) translations info))
1811 (tags (and (plist-get info :with-tags)
1812 (org-export-get-tags headline info)))
1813 (headline-label (concat "sec-" (mapconcat 'number-to-string
1814 headline-number "-")))
1815 (format-function (cond
1816 ((functionp format-function) format-function)
1817 ((functionp org-odt-format-headline-function)
1818 (function*
1819 (lambda (todo todo-type priority text tags
1820 &allow-other-keys)
1821 (funcall org-odt-format-headline-function
1822 todo todo-type priority text tags))))
1823 (t 'org-odt-format-headline))))
1824 (apply format-function
1825 todo todo-type priority text tags
1826 :headline-label headline-label :level level
1827 :section-number section-number extra-keys)))
1829 (defun org-odt-headline (headline contents info)
1830 "Transcode a HEADLINE element from Org to ODT.
1831 CONTENTS holds the contents of the headline. INFO is a plist
1832 holding contextual information."
1833 ;; Case 1: This is a footnote section: ignore it.
1834 (unless (org-element-property :footnote-section-p headline)
1835 (let* ((text (org-export-data (org-element-property :title headline) info))
1836 ;; Create the headline text.
1837 (full-text (org-odt-format-headline--wrap headline nil info))
1838 ;; Get level relative to current parsed data.
1839 (level (org-export-get-relative-level headline info))
1840 ;; Get canonical label for the headline.
1841 (id (concat "sec-" (mapconcat 'number-to-string
1842 (org-export-get-headline-number
1843 headline info) "-")))
1844 ;; Get user-specified labels for the headline.
1845 (extra-ids (list (org-element-property :CUSTOM_ID headline)
1846 (org-element-property :ID headline)))
1847 ;; Extra targets.
1848 (extra-targets
1849 (mapconcat (lambda (x)
1850 (when x
1851 (let ((x (if (org-uuidgen-p x) (concat "ID-" x) x)))
1852 (org-odt--target
1853 "" (org-export-solidify-link-text x)))))
1854 extra-ids ""))
1855 ;; Title.
1856 (anchored-title (org-odt--target full-text id)))
1857 (cond
1858 ;; Case 2. This is a deep sub-tree: export it as a list item.
1859 ;; Also export as items headlines for which no section
1860 ;; format has been found.
1861 ((org-export-low-level-p headline info)
1862 ;; Build the real contents of the sub-tree.
1863 (concat
1864 (and (org-export-first-sibling-p headline info)
1865 (format "\n<text:list text:style-name=\"%s\" %s>"
1866 ;; Choose style based on list type.
1867 (if (org-export-numbered-headline-p headline info)
1868 "OrgNumberedList" "OrgBulletedList")
1869 ;; If top-level list, re-start numbering. Otherwise,
1870 ;; continue numbering.
1871 (format "text:continue-numbering=\"%s\""
1872 (let* ((parent (org-export-get-parent-headline
1873 headline)))
1874 (if (and parent
1875 (org-export-low-level-p parent info))
1876 "true" "false")))))
1877 (let ((headline-has-table-p
1878 (let ((section (assq 'section (org-element-contents headline))))
1879 (assq 'table (and section (org-element-contents section))))))
1880 (format "\n<text:list-item>\n%s\n%s"
1881 (concat
1882 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1883 "Text_20_body"
1884 (concat extra-targets anchored-title))
1885 contents)
1886 (if headline-has-table-p
1887 "</text:list-header>"
1888 "</text:list-item>")))
1889 (and (org-export-last-sibling-p headline info)
1890 "</text:list>")))
1891 ;; Case 3. Standard headline. Export it as a section.
1893 (concat
1894 (format
1895 "\n<text:h text:style-name=\"%s\" text:outline-level=\"%s\">%s</text:h>"
1896 (format "Heading_20_%s" level)
1897 level
1898 (concat extra-targets anchored-title))
1899 contents))))))
1902 ;;;; Horizontal Rule
1904 (defun org-odt-horizontal-rule (horizontal-rule contents info)
1905 "Transcode an HORIZONTAL-RULE object from Org to ODT.
1906 CONTENTS is nil. INFO is a plist holding contextual information."
1907 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1908 "Horizontal_20_Line" ""))
1911 ;;;; Inline Babel Call
1913 ;; Inline Babel Calls are ignored.
1916 ;;;; Inline Src Block
1918 (defun org-odt--find-verb-separator (s)
1919 "Return a character not used in string S.
1920 This is used to choose a separator for constructs like \\verb."
1921 (let ((ll "~,./?;':\"|!@#%^&-_=+abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ<>()[]{}"))
1922 (loop for c across ll
1923 when (not (string-match (regexp-quote (char-to-string c)) s))
1924 return (char-to-string c))))
1926 (defun org-odt-inline-src-block (inline-src-block contents info)
1927 "Transcode an INLINE-SRC-BLOCK element from Org to ODT.
1928 CONTENTS holds the contents of the item. INFO is a plist holding
1929 contextual information."
1930 (let* ((org-lang (org-element-property :language inline-src-block))
1931 (code (org-element-property :value inline-src-block))
1932 (separator (org-odt--find-verb-separator code)))
1933 (error "FIXME")))
1936 ;;;; Inlinetask
1938 (defun org-odt-inlinetask (inlinetask contents info)
1939 "Transcode an INLINETASK element from Org to ODT.
1940 CONTENTS holds the contents of the block. INFO is a plist
1941 holding contextual information."
1942 (cond
1943 ;; If `org-odt-format-inlinetask-function' is provided, call it
1944 ;; with appropriate arguments.
1945 ((functionp org-odt-format-inlinetask-function)
1946 (let ((format-function
1947 (function*
1948 (lambda (todo todo-type priority text tags
1949 &key contents &allow-other-keys)
1950 (funcall org-odt-format-inlinetask-function
1951 todo todo-type priority text tags contents)))))
1952 (org-odt-format-headline--wrap
1953 inlinetask nil info format-function :contents contents)))
1954 ;; Otherwise, use a default template.
1956 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1957 "Text_20_body"
1958 (org-odt--textbox
1959 (concat
1960 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
1961 "OrgInlineTaskHeading"
1962 (org-odt-format-headline--wrap inlinetask nil info))
1963 contents)
1964 nil nil "OrgInlineTaskFrame" " style:rel-width=\"100%\"")))))
1966 ;;;; Italic
1968 (defun org-odt-italic (italic contents info)
1969 "Transcode ITALIC from Org to ODT.
1970 CONTENTS is the text with italic markup. INFO is a plist holding
1971 contextual information."
1972 (format "<text:span text:style-name=\"%s\">%s</text:span>"
1973 "Emphasis" contents))
1976 ;;;; Item
1978 (defun org-odt-item (item contents info)
1979 "Transcode an ITEM element from Org to ODT.
1980 CONTENTS holds the contents of the item. INFO is a plist holding
1981 contextual information."
1982 (let* ((plain-list (org-export-get-parent item))
1983 (type (org-element-property :type plain-list))
1984 (counter (org-element-property :counter item))
1985 (tag (let ((tag (org-element-property :tag item)))
1986 (and tag
1987 (concat (org-odt--checkbox item)
1988 (org-export-data tag info))))))
1989 (case type
1990 ((ordered unordered descriptive-1 descriptive-2)
1991 (format "\n<text:list-item>\n%s\n%s"
1992 contents
1993 (let* ((--element-has-a-table-p
1994 (function
1995 (lambda (element info)
1996 (loop for el in (org-element-contents element)
1997 thereis (eq (org-element-type el) 'table))))))
1998 (cond
1999 ((funcall --element-has-a-table-p item info)
2000 "</text:list-header>")
2001 (t "</text:list-item>")))))
2002 (t (error "Unknown list type: %S" type)))))
2004 ;;;; Keyword
2006 (defun org-odt-keyword (keyword contents info)
2007 "Transcode a KEYWORD element from Org to ODT.
2008 CONTENTS is nil. INFO is a plist holding contextual information."
2009 (let ((key (org-element-property :key keyword))
2010 (value (org-element-property :value keyword)))
2011 (cond
2012 ((string= key "ODT") value)
2013 ((string= key "INDEX")
2014 ;; FIXME
2015 (ignore))
2016 ((string= key "TARGET") nil)
2017 ((string= key "TOC")
2018 (let ((value (downcase value)))
2019 (cond
2020 ((string-match "\\<headlines\\>" value)
2021 (let ((depth (or (and (string-match "[0-9]+" value)
2022 (string-to-number (match-string 0 value)))
2023 (plist-get info :with-toc))))
2024 (when (wholenump depth) (org-odt-toc depth info))))
2025 ((member value '("tables" "figures" "listings"))
2026 ;; FIXME
2027 (ignore))))))))
2030 ;;;; Latex Environment
2033 ;; (eval-after-load 'ox-odt '(ad-deactivate 'org-format-latex-as-mathml))
2034 ;; (defadvice org-format-latex-as-mathml ; FIXME
2035 ;; (after org-odt-protect-latex-fragment activate)
2036 ;; "Encode LaTeX fragment as XML.
2037 ;; Do this when translation to MathML fails."
2038 ;; (unless (> (length ad-return-value) 0)
2039 ;; (setq ad-return-value (org-odt--encode-plain-text (ad-get-arg 0)))))
2041 (defun org-odt-latex-environment (latex-environment contents info)
2042 "Transcode a LATEX-ENVIRONMENT element from Org to ODT.
2043 CONTENTS is nil. INFO is a plist holding contextual information."
2044 (let* ((latex-frag (org-remove-indentation
2045 (org-element-property :value latex-environment))))
2046 (org-odt-do-format-code latex-frag)))
2049 ;;;; Latex Fragment
2051 ;; (when latex-frag ; FIXME
2052 ;; (setq href (org-propertize href :title "LaTeX Fragment"
2053 ;; :description latex-frag)))
2054 ;; handle verbatim
2055 ;; provide descriptions
2057 (defun org-odt-latex-fragment (latex-fragment contents info)
2058 "Transcode a LATEX-FRAGMENT object from Org to ODT.
2059 CONTENTS is nil. INFO is a plist holding contextual information."
2060 (let* ((latex-frag (org-element-property :value latex-fragment))
2061 (processing-type (plist-get info :with-latex)))
2062 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2063 "OrgCode" (org-odt--encode-plain-text latex-frag t))))
2066 ;;;; Line Break
2068 (defun org-odt-line-break (line-break contents info)
2069 "Transcode a LINE-BREAK object from Org to ODT.
2070 CONTENTS is nil. INFO is a plist holding contextual information."
2071 "<text:line-break/>\n")
2074 ;;;; Link
2076 ;;;; Links :: Label references
2078 (defun org-odt--enumerate (element info &optional predicate n)
2079 (when predicate (assert (funcall predicate element info)))
2080 (let* ((--numbered-parent-headline-at-<=-n
2081 (function
2082 (lambda (element n info)
2083 (loop for x in (org-export-get-genealogy element)
2084 thereis (and (eq (org-element-type x) 'headline)
2085 (<= (org-export-get-relative-level x info) n)
2086 (org-export-numbered-headline-p x info)
2087 x)))))
2088 (--enumerate
2089 (function
2090 (lambda (element scope info &optional predicate)
2091 (let ((counter 0))
2092 (org-element-map (or scope (plist-get info :parse-tree))
2093 (org-element-type element)
2094 (lambda (el)
2095 (and (or (not predicate) (funcall predicate el info))
2096 (incf counter)
2097 (eq element el)
2098 counter))
2099 info 'first-match)))))
2100 (scope (funcall --numbered-parent-headline-at-<=-n
2101 element (or n org-odt-display-outline-level) info))
2102 (ordinal (funcall --enumerate element scope info predicate))
2103 (tag
2104 (concat
2105 ;; Section number.
2106 (and scope
2107 (mapconcat 'number-to-string
2108 (org-export-get-headline-number scope info) "."))
2109 ;; Separator.
2110 (and scope ".")
2111 ;; Ordinal.
2112 (number-to-string ordinal))))
2113 tag))
2115 (defun org-odt-format-label (element info op)
2116 (assert (memq (org-element-type element) '(link table src-block paragraph)))
2117 (let* ((caption-from
2118 (case (org-element-type element)
2119 (link (org-export-get-parent-element element))
2120 (t element)))
2121 ;; Get label and caption.
2122 (label (org-element-property :name caption-from))
2123 (caption (org-export-get-caption caption-from))
2124 (short-caption (org-export-get-caption caption-from t))
2125 ;; Transcode captions.
2126 (caption (and caption (org-export-data caption info)))
2127 ;; Currently short caption are sneaked in as object names.
2129 ;; The advantages are:
2131 ;; - Table Of Contents: Currently, there is no support for
2132 ;; building TOC for figures, listings and tables. See
2133 ;; `org-odt-keyword'. User instead has to rely on
2134 ;; external application for building such indices. Within
2135 ;; LibreOffice, building an "Illustration Index" or "Index
2136 ;; of Tables" will create a table with long captions (only)
2137 ;; and building a table with "Object names" will create a
2138 ;; table with short captions.
2140 ;; - Easy navigation: In LibreOffice, object names are
2141 ;; offered via the navigation bar. This way one can
2142 ;; quickly locate and jump to object of his choice in the
2143 ;; exported document.
2145 ;; The main disadvantage is that there cannot be any markups
2146 ;; within object names i.e., one cannot embolden, italicize
2147 ;; or underline text within short caption. So suppress
2148 ;; generation of <text:span >...</text:span> and other
2149 ;; markups by overriding the default translators. We
2150 ;; probably shouldn't be suppressing translators for all
2151 ;; elements in `org-element-all-objects', but for now this
2152 ;; will do.
2153 (short-caption
2154 (let ((short-caption (or short-caption caption))
2155 (translations (nconc (mapcar
2156 (lambda (type)
2157 (cons type (lambda (data contents info)
2158 contents)))
2159 org-element-all-objects)
2160 (plist-get info :translate-alist))))
2161 (when short-caption
2162 (org-export-data-with-translations short-caption
2163 translations info)))))
2164 (when (or label caption)
2165 (let* ((default-category
2166 (case (org-element-type element)
2167 (table "__Table__")
2168 (src-block "__Listing__")
2169 ((link paragraph)
2170 (cond
2171 ((org-odt--enumerable-latex-image-p element info)
2172 "__DvipngImage__")
2173 ((org-odt--enumerable-image-p element info)
2174 "__Figure__")
2175 ((org-odt--enumerable-formula-p element info)
2176 "__MathFormula__")
2177 (t (error "Don't know how to format label for link: %S"
2178 element))))
2179 (t (error "Don't know how to format label for element type: %s"
2180 (org-element-type element)))))
2181 seqno)
2182 (assert default-category)
2183 (destructuring-bind (counter label-style category predicate)
2184 (assoc-default default-category org-odt-category-map-alist)
2185 ;; Compute sequence number of the element.
2186 (setq seqno (org-odt--enumerate element info predicate))
2187 ;; Localize category string.
2188 (setq category (org-export-translate category :utf-8 info))
2189 (case op
2190 ;; Case 1: Handle Label definition.
2191 (definition
2192 ;; Assign an internal label, if user has not provided one
2193 (setq label (or label (format "%s-%s" default-category seqno)))
2194 (setq label (org-export-solidify-link-text label))
2195 (cons
2196 (concat
2197 ;; Sneak in a bookmark. The bookmark is used when the
2198 ;; labeled element is referenced with a link that
2199 ;; provides it's own description.
2200 (format "\n<text:bookmark text:name=\"%s\"/>" label)
2201 ;; Label definition: Typically formatted as below:
2202 ;; CATEGORY SEQ-NO: LONG CAPTION
2203 (format-spec
2204 (cadr (assoc-string label-style org-odt-label-styles t))
2205 `((?e . ,category)
2206 (?n . ,(format
2207 "<text:sequence text:ref-name=\"%s\" text:name=\"%s\" text:formula=\"ooow:%s+1\" style:num-format=\"1\">%s</text:sequence>"
2208 label counter counter seqno))
2209 (?c . ,(or caption "")))))
2210 short-caption))
2211 ;; Case 2: Handle Label reference.
2212 (reference
2213 (assert label)
2214 (setq label (org-export-solidify-link-text label))
2215 (let* ((fmt (cddr (assoc-string label-style org-odt-label-styles t)))
2216 (fmt1 (car fmt))
2217 (fmt2 (cadr fmt)))
2218 (format "<text:sequence-ref text:reference-format=\"%s\" text:ref-name=\"%s\">%s</text:sequence-ref>"
2219 fmt1 label (format-spec fmt2 `((?e . ,category)
2220 (?n . ,seqno))))))
2221 (t (error "Unknown %S on label" op))))))))
2224 ;;;; Links :: Inline Images
2226 (defun org-odt--copy-image-file (path)
2227 "Returns the internal name of the file"
2228 (let* ((image-type (file-name-extension path))
2229 (media-type (format "image/%s" image-type))
2230 (target-dir "Images/")
2231 (target-file
2232 (format "%s%04d.%s" target-dir
2233 (incf org-odt-embedded-images-count) image-type)))
2234 (message "Embedding %s as %s ..."
2235 (substring-no-properties path) target-file)
2237 (when (= 1 org-odt-embedded-images-count)
2238 (make-directory (concat org-odt-zip-dir target-dir))
2239 (org-odt-create-manifest-file-entry "" target-dir))
2241 (copy-file path (concat org-odt-zip-dir target-file) 'overwrite)
2242 (org-odt-create-manifest-file-entry media-type target-file)
2243 target-file))
2245 (defun org-odt--image-size (file &optional user-width
2246 user-height scale dpi embed-as)
2247 (let* ((--pixels-to-cms
2248 (function (lambda (pixels dpi)
2249 (let ((cms-per-inch 2.54)
2250 (inches (/ pixels dpi)))
2251 (* cms-per-inch inches)))))
2252 (--size-in-cms
2253 (function
2254 (lambda (size-in-pixels dpi)
2255 (and size-in-pixels
2256 (cons (funcall --pixels-to-cms (car size-in-pixels) dpi)
2257 (funcall --pixels-to-cms (cdr size-in-pixels) dpi))))))
2258 (dpi (or dpi org-odt-pixels-per-inch))
2259 (anchor-type (or embed-as "paragraph"))
2260 (user-width (and (not scale) user-width))
2261 (user-height (and (not scale) user-height))
2262 (size
2263 (and
2264 (not (and user-height user-width))
2266 ;; Use Imagemagick.
2267 (and (executable-find "identify")
2268 (let ((size-in-pixels
2269 (let ((dim (shell-command-to-string
2270 (format "identify -format \"%%w:%%h\" \"%s\""
2271 file))))
2272 (when (string-match "\\([0-9]+\\):\\([0-9]+\\)" dim)
2273 (cons (string-to-number (match-string 1 dim))
2274 (string-to-number (match-string 2 dim)))))))
2275 (funcall --size-in-cms size-in-pixels dpi)))
2276 ;; Use Emacs.
2277 (let ((size-in-pixels
2278 (ignore-errors ; Emacs could be in batch mode
2279 (clear-image-cache)
2280 (image-size (create-image file) 'pixels))))
2281 (funcall --size-in-cms size-in-pixels dpi))
2282 ;; Use hard-coded values.
2283 (cdr (assoc-string anchor-type
2284 org-odt-default-image-sizes-alist))
2285 ;; Error out.
2286 (error "Cannot determine image size, aborting"))))
2287 (width (car size)) (height (cdr size)))
2288 (cond
2289 (scale
2290 (setq width (* width scale) height (* height scale)))
2291 ((and user-height user-width)
2292 (setq width user-width height user-height))
2293 (user-height
2294 (setq width (* user-height (/ width height)) height user-height))
2295 (user-width
2296 (setq height (* user-width (/ height width)) width user-width))
2297 (t (ignore)))
2298 ;; ensure that an embedded image fits comfortably within a page
2299 (let ((max-width (car org-odt-max-image-size))
2300 (max-height (cdr org-odt-max-image-size)))
2301 (when (or (> width max-width) (> height max-height))
2302 (let* ((scale1 (/ max-width width))
2303 (scale2 (/ max-height height))
2304 (scale (min scale1 scale2)))
2305 (setq width (* scale width) height (* scale height)))))
2306 (cons width height)))
2308 (defun org-odt-link--inline-image (element info)
2309 "Return ODT code for an inline image.
2310 LINK is the link pointing to the inline image. INFO is a plist
2311 used as a communication channel."
2312 (assert (eq (org-element-type element) 'link))
2313 (let* ((src (let* ((type (org-element-property :type element))
2314 (raw-path (org-element-property :path element)))
2315 (cond ((member type '("http" "https"))
2316 (concat type ":" raw-path))
2317 ((file-name-absolute-p raw-path)
2318 (expand-file-name raw-path))
2319 (t raw-path))))
2320 (src-expanded (if (file-name-absolute-p src) src
2321 (expand-file-name src (file-name-directory
2322 (plist-get info :input-file)))))
2323 (href (format
2324 "\n<draw:image xlink:href=\"%s\" xlink:type=\"simple\" xlink:show=\"embed\" xlink:actuate=\"onLoad\"/>"
2325 (org-odt--copy-image-file src-expanded)))
2326 ;; Extract attributes from #+ATTR_ODT line.
2327 (attr-from (case (org-element-type element)
2328 (link (org-export-get-parent-element element))
2329 (t element)))
2330 ;; Convert attributes to a plist.
2331 (attr-plist (org-export-read-attribute :attr_odt attr-from))
2332 ;; Handle `:anchor', `:style' and `:attributes' properties.
2333 (user-frame-anchor
2334 (car (assoc-string (plist-get attr-plist :anchor)
2335 '(("as-char") ("paragraph") ("page")) t)))
2336 (user-frame-style
2337 (and user-frame-anchor (plist-get attr-plist :style)))
2338 (user-frame-attrs
2339 (and user-frame-anchor (plist-get attr-plist :attributes)))
2340 (user-frame-params
2341 (list user-frame-style user-frame-attrs user-frame-anchor))
2342 ;; (embed-as (or embed-as user-frame-anchor "paragraph"))
2343 ;; extrac
2344 ;; handle `:width', `:height' and `:scale' properties.
2345 (size (org-odt--image-size
2346 src-expanded (plist-get attr-plist :width)
2347 (plist-get attr-plist :height)
2348 (plist-get attr-plist :scale) nil ;; embed-as
2349 "paragraph" ; FIXME
2351 (width (car size)) (height (cdr size))
2352 (standalone-link-p (org-odt--standalone-link-p element info))
2353 (embed-as (if standalone-link-p "paragraph" "as-char"))
2354 (captions (org-odt-format-label element info 'definition))
2355 (caption (car captions)) (short-caption (cdr captions))
2356 (entity (concat (and caption "Captioned") embed-as "Image"))
2357 ;; Check if this link was created by LaTeX-to-PNG converter.
2358 (replaces (org-element-property
2359 :replaces (if (not standalone-link-p) element
2360 (org-export-get-parent-element element))))
2361 ;; If yes, note down the type of the element - LaTeX Fragment
2362 ;; or LaTeX environment. It will go in to frame title.
2363 (title (and replaces (capitalize
2364 (symbol-name (org-element-type replaces)))))
2366 ;; If yes, note down it's contents. It will go in to frame
2367 ;; description. This quite useful for debugging.
2368 (desc (and replaces (org-element-property :value replaces))))
2369 (org-odt--render-image/formula entity href width height
2370 captions user-frame-params title desc)))
2373 ;;;; Links :: Math formula
2375 (defun org-odt-link--inline-formula (element info)
2376 (let* ((src (let* ((type (org-element-property :type element))
2377 (raw-path (org-element-property :path element)))
2378 (cond
2379 ((file-name-absolute-p raw-path)
2380 (expand-file-name raw-path))
2381 (t raw-path))))
2382 (src-expanded (if (file-name-absolute-p src) src
2383 (expand-file-name src (file-name-directory
2384 (plist-get info :input-file)))))
2385 (href
2386 (format
2387 "\n<draw:object %s xlink:href=\"%s\" xlink:type=\"simple\"/>"
2388 " xlink:show=\"embed\" xlink:actuate=\"onLoad\""
2389 (file-name-directory (org-odt--copy-formula-file src-expanded))))
2390 (standalone-link-p (org-odt--standalone-link-p element info))
2391 (embed-as (if standalone-link-p 'paragraph 'character))
2392 (captions (org-odt-format-label element info 'definition))
2393 (caption (car captions)) (short-caption (cdr captions))
2394 ;; Check if this link was created by LaTeX-to-MathML
2395 ;; converter.
2396 (replaces (org-element-property
2397 :replaces (if (not standalone-link-p) element
2398 (org-export-get-parent-element element))))
2399 ;; If yes, note down the type of the element - LaTeX Fragment
2400 ;; or LaTeX environment. It will go in to frame title.
2401 (title (and replaces (capitalize
2402 (symbol-name (org-element-type replaces)))))
2404 ;; If yes, note down it's contents. It will go in to frame
2405 ;; description. This quite useful for debugging.
2406 (desc (and replaces (org-element-property :value replaces)))
2407 width height)
2408 (cond
2409 ((eq embed-as 'character)
2410 (org-odt--render-image/formula "InlineFormula" href width height
2411 nil nil title desc))
2413 (let* ((equation (org-odt--render-image/formula
2414 "CaptionedDisplayFormula" href width height
2415 captions nil title desc))
2416 (label
2417 (let* ((org-odt-category-map-alist
2418 '(("__MathFormula__" "Text" "math-label" "Equation"
2419 org-odt--enumerable-formula-p))))
2420 (car (org-odt-format-label element info 'definition)))))
2421 (concat equation "<text:tab/>" label))))))
2423 (defun org-odt--copy-formula-file (src-file)
2424 "Returns the internal name of the file"
2425 (let* ((target-dir (format "Formula-%04d/"
2426 (incf org-odt-embedded-formulas-count)))
2427 (target-file (concat target-dir "content.xml")))
2428 ;; Create a directory for holding formula file. Also enter it in
2429 ;; to manifest.
2430 (make-directory (concat org-odt-zip-dir target-dir))
2431 (org-odt-create-manifest-file-entry
2432 "application/vnd.oasis.opendocument.formula" target-dir "1.2")
2433 ;; Copy over the formula file from user directory to zip
2434 ;; directory.
2435 (message "Embedding %s as %s ..." src-file target-file)
2436 (let ((case-fold-search nil))
2437 (cond
2438 ;; Case 1: Mathml.
2439 ((string-match "\\.\\(mathml\\|mml\\)\\'" src-file)
2440 (copy-file src-file (concat org-odt-zip-dir target-file) 'overwrite))
2441 ;; Case 2: OpenDocument formula.
2442 ((string-match "\\.odf\\'" src-file)
2443 (org-odt--zip-extract src-file "content.xml"
2444 (concat org-odt-zip-dir target-dir)))
2445 (t (error "%s is not a formula file" src-file))))
2446 ;; Enter the formula file in to manifest.
2447 (org-odt-create-manifest-file-entry "text/xml" target-file)
2448 target-file))
2450 ;;;; Targets
2452 (defun org-odt--render-image/formula (cfg-key href width height &optional
2453 captions user-frame-params
2454 &rest title-and-desc)
2455 (let* ((frame-cfg-alist
2456 ;; Each element of this alist is of the form (CFG-HANDLE
2457 ;; INNER-FRAME-PARAMS OUTER-FRAME-PARAMS).
2459 ;; CFG-HANDLE is the key to the alist.
2461 ;; INNER-FRAME-PARAMS and OUTER-FRAME-PARAMS specify the
2462 ;; frame params for INNER-FRAME and OUTER-FRAME
2463 ;; respectively. See below.
2465 ;; Configurations that are meant to be applied to
2466 ;; non-captioned image/formula specifies no
2467 ;; OUTER-FRAME-PARAMS.
2469 ;; TERMINOLOGY
2470 ;; ===========
2471 ;; INNER-FRAME :: Frame that directly surrounds an
2472 ;; image/formula.
2474 ;; OUTER-FRAME :: Frame that encloses the INNER-FRAME. This
2475 ;; frame also contains the caption, if any.
2477 ;; FRAME-PARAMS :: List of the form (FRAME-STYLE-NAME
2478 ;; FRAME-ATTRIBUTES FRAME-ANCHOR). Note
2479 ;; that these are the last three arguments
2480 ;; to `org-odt--frame'.
2482 ;; Note that an un-captioned image/formula requires just an
2483 ;; INNER-FRAME, while a captioned image/formula requires
2484 ;; both an INNER and an OUTER-FRAME.
2485 '(("As-CharImage" ("OrgInlineImage" nil "as-char"))
2486 ("ParagraphImage" ("OrgDisplayImage" nil "paragraph"))
2487 ("PageImage" ("OrgPageImage" nil "page"))
2488 ("CaptionedAs-CharImage"
2489 ("OrgCaptionedImage"
2490 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2491 ("OrgInlineImage" nil "as-char"))
2492 ("CaptionedParagraphImage"
2493 ("OrgCaptionedImage"
2494 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2495 ("OrgImageCaptionFrame" nil "paragraph"))
2496 ("CaptionedPageImage"
2497 ("OrgCaptionedImage"
2498 " style:rel-width=\"100%\" style:rel-height=\"scale\"" "paragraph")
2499 ("OrgPageImageCaptionFrame" nil "page"))
2500 ("InlineFormula" ("OrgInlineFormula" nil "as-char"))
2501 ("DisplayFormula" ("OrgDisplayFormula" nil "as-char"))
2502 ("CaptionedDisplayFormula"
2503 ("OrgCaptionedFormula" nil "paragraph")
2504 ("OrgFormulaCaptionFrame" nil "paragraph"))))
2505 (caption (car captions)) (short-caption (cdr captions))
2506 ;; Retrieve inner and outer frame params, from configuration.
2507 (frame-cfg (assoc-string cfg-key frame-cfg-alist t))
2508 (inner (nth 1 frame-cfg))
2509 (outer (nth 2 frame-cfg))
2510 ;; User-specified frame params (from #+ATTR_ODT spec)
2511 (user user-frame-params)
2512 (--merge-frame-params (function
2513 (lambda (default user)
2514 "Merge default and user frame params."
2515 (if (not user) default
2516 (assert (= (length default) 3))
2517 (assert (= (length user) 3))
2518 (loop for u in user
2519 for d in default
2520 collect (or u d)))))))
2521 (cond
2522 ;; Case 1: Image/Formula has no caption.
2523 ;; There is only one frame, one that surrounds the image
2524 ;; or formula.
2525 ((not caption)
2526 ;; Merge user frame params with that from configuration.
2527 (setq inner (funcall --merge-frame-params inner user))
2528 (apply 'org-odt--frame href width height
2529 (append inner title-and-desc)))
2530 ;; Case 2: Image/Formula is captioned or labeled.
2531 ;; There are two frames: The inner one surrounds the
2532 ;; image or formula. The outer one contains the
2533 ;; caption/sequence number.
2535 ;; Merge user frame params with outer frame params.
2536 (setq outer (funcall --merge-frame-params outer user))
2537 ;; Short caption, if specified, goes as part of inner frame.
2538 (setq inner (let ((frame-params (copy-sequence inner)))
2539 (setcar (cdr frame-params)
2540 (concat
2541 (cadr frame-params)
2542 (when short-caption
2543 (format " draw:name=\"%s\" " short-caption))))
2544 frame-params))
2545 (apply 'org-odt--textbox
2546 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2547 "Illustration"
2548 (concat
2549 (apply 'org-odt--frame href width height
2550 (append inner title-and-desc))
2551 caption))
2552 width height outer)))))
2554 (defun org-odt--enumerable-p (element info)
2555 ;; Element should have a caption or label.
2556 (or (org-element-property :caption element)
2557 (org-element-property :name element)))
2559 (defun org-odt--enumerable-image-p (element info)
2560 (org-odt--standalone-link-p
2561 element info
2562 ;; Paragraph should have a caption or label. It SHOULD NOT be a
2563 ;; replacement element. (i.e., It SHOULD NOT be a result of LaTeX
2564 ;; processing.)
2565 (lambda (p)
2566 (and (not (org-element-property :replaces p))
2567 (or (org-element-property :caption p)
2568 (org-element-property :name p))))
2569 ;; Link should point to an image file.
2570 (lambda (l)
2571 (assert (eq (org-element-type l) 'link))
2572 (org-export-inline-image-p l org-odt-inline-image-rules))))
2574 (defun org-odt--enumerable-latex-image-p (element info)
2575 (org-odt--standalone-link-p
2576 element info
2577 ;; Paragraph should have a caption or label. It SHOULD also be a
2578 ;; replacement element. (i.e., It SHOULD be a result of LaTeX
2579 ;; processing.)
2580 (lambda (p)
2581 (and (org-element-property :replaces p)
2582 (or (org-element-property :caption p)
2583 (org-element-property :name p))))
2584 ;; Link should point to an image file.
2585 (lambda (l)
2586 (assert (eq (org-element-type l) 'link))
2587 (org-export-inline-image-p l org-odt-inline-image-rules))))
2589 (defun org-odt--enumerable-formula-p (element info)
2590 (org-odt--standalone-link-p
2591 element info
2592 ;; Paragraph should have a caption or label.
2593 (lambda (p)
2594 (or (org-element-property :caption p)
2595 (org-element-property :name p)))
2596 ;; Link should point to a MathML or ODF file.
2597 (lambda (l)
2598 (assert (eq (org-element-type l) 'link))
2599 (org-export-inline-image-p l org-odt-inline-formula-rules))))
2601 (defun org-odt--standalone-link-p (element info &optional
2602 paragraph-predicate
2603 link-predicate)
2604 "Test if ELEMENT is a standalone link for the purpose ODT export.
2605 INFO is a plist holding contextual information.
2607 Return non-nil, if ELEMENT is of type paragraph satisfying
2608 PARAGRAPH-PREDICATE and it's sole content, save for whitespaces,
2609 is a link that satisfies LINK-PREDICATE.
2611 Return non-nil, if ELEMENT is of type link satisfying
2612 LINK-PREDICATE and it's containing paragraph satisfies
2613 PARAGRAPH-PREDICATE inaddtion to having no other content save for
2614 leading and trailing whitespaces.
2616 Return nil, otherwise."
2617 (let ((p (case (org-element-type element)
2618 (paragraph element)
2619 (link (and (or (not link-predicate)
2620 (funcall link-predicate element))
2621 (org-export-get-parent element)))
2622 (t nil))))
2623 (when (and p (eq (org-element-type p) 'paragraph))
2624 (when (or (not paragraph-predicate)
2625 (funcall paragraph-predicate p))
2626 (let ((contents (org-element-contents p)))
2627 (loop for x in contents
2628 with inline-image-count = 0
2629 always (case (org-element-type x)
2630 (plain-text
2631 (not (org-string-nw-p x)))
2632 (link
2633 (and (or (not link-predicate)
2634 (funcall link-predicate x))
2635 (= (incf inline-image-count) 1)))
2636 (t nil))))))))
2638 (defun org-odt-link--infer-description (destination info)
2639 ;; DESTINATION is a HEADLINE, a "<<target>>" or an element (like
2640 ;; paragraph, verse-block etc) to which a "#+NAME: label" can be
2641 ;; attached. Note that labels that are attached to captioned
2642 ;; entities - inline images, math formulae and tables - get resolved
2643 ;; as part of `org-odt-format-label' and `org-odt--enumerate'.
2645 ;; Create a cross-reference to DESTINATION but make best-efforts to
2646 ;; create a *meaningful* description. Check item numbers, section
2647 ;; number and section title in that order.
2649 ;; NOTE: Counterpart of `org-export-get-ordinal'.
2650 ;; FIXME: Handle footnote-definition footnote-reference?
2651 (let* ((genealogy (org-export-get-genealogy destination))
2652 (data (reverse genealogy))
2653 (label (case (org-element-type destination)
2654 (headline
2655 (format "sec-%s" (mapconcat 'number-to-string
2656 (org-export-get-headline-number
2657 destination info) "-")))
2658 (target
2659 (org-element-property :value destination))
2660 (t (error "FIXME: Resolve %S" destination)))))
2662 (let* ( ;; Locate top-level list.
2663 (top-level-list
2664 (loop for x on data
2665 when (eq (org-element-type (car x)) 'plain-list)
2666 return x))
2667 ;; Get list item nos.
2668 (item-numbers
2669 (loop for (plain-list item . rest) on top-level-list by #'cddr
2670 until (not (eq (org-element-type plain-list) 'plain-list))
2671 collect (when (eq (org-element-property :type
2672 plain-list)
2673 'ordered)
2674 (1+ (length (org-export-get-previous-element
2675 item info t))))))
2676 ;; Locate top-most listified headline.
2677 (listified-headlines
2678 (loop for x on data
2679 when (and (eq (org-element-type (car x)) 'headline)
2680 (org-export-low-level-p (car x) info))
2681 return x))
2682 ;; Get listified headline numbers.
2683 (listified-headline-nos
2684 (loop for el in listified-headlines
2685 when (eq (org-element-type el) 'headline)
2686 collect (when (org-export-numbered-headline-p el info)
2687 (1+ (length (org-export-get-previous-element
2688 el info t)))))))
2689 ;; Combine item numbers from both the listified headlines and
2690 ;; regular list items.
2692 ;; Case 1: Check if all the parents of list item are numbered.
2693 ;; If yes, link to the item proper.
2694 (let ((item-numbers (append listified-headline-nos item-numbers)))
2695 (when (and item-numbers (not (memq nil item-numbers)))
2696 (format "<text:bookmark-ref text:reference-format=\"number-all-superior\" text:ref-name=\"%s\">%s</text:bookmark-ref>"
2697 (org-export-solidify-link-text label)
2698 (mapconcat (lambda (n) (if (not n) " "
2699 (concat (number-to-string n) ".")))
2700 item-numbers "")))))
2701 ;; Case 2: Locate a regular and numbered headline in the
2702 ;; hierarchy. Display it's section number.
2703 (let ((headline (loop for el in (cons destination genealogy)
2704 when (and (eq (org-element-type el) 'headline)
2705 (not (org-export-low-level-p el info))
2706 (org-export-numbered-headline-p el info))
2707 return el)))
2708 ;; We found one.
2709 (when headline
2710 (format "<text:bookmark-ref text:reference-format=\"chapter\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2711 (org-export-solidify-link-text label)
2712 (mapconcat 'number-to-string (org-export-get-headline-number
2713 headline info) "."))))
2714 ;; Case 4: Locate a regular headline in the hierarchy. Display
2715 ;; it's title.
2716 (let ((headline (loop for el in (cons destination genealogy)
2717 when (and (eq (org-element-type el) 'headline)
2718 (not (org-export-low-level-p el info)))
2719 return el)))
2720 ;; We found one.
2721 (when headline
2722 (format "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2723 (org-export-solidify-link-text label)
2724 (let ((title (org-element-property :title headline)))
2725 (org-export-data title info)))))
2726 (error "FIXME?"))))
2728 (defun org-odt-link (link desc info)
2729 "Transcode a LINK object from Org to ODT.
2731 DESC is the description part of the link, or the empty string.
2732 INFO is a plist holding contextual information. See
2733 `org-export-data'."
2734 (let* ((type (org-element-property :type link))
2735 (raw-path (org-element-property :path link))
2736 ;; Ensure DESC really exists, or set it to nil.
2737 (desc (and (not (string= desc "")) desc))
2738 (imagep (org-export-inline-image-p
2739 link org-odt-inline-image-rules))
2740 (path (cond
2741 ((member type '("http" "https" "ftp" "mailto"))
2742 (concat type ":" raw-path))
2743 ((string= type "file")
2744 (if (file-name-absolute-p raw-path)
2745 (concat "file://" (expand-file-name raw-path))
2746 (concat "file://" raw-path)))
2747 (t raw-path)))
2748 protocol)
2749 (cond
2750 ;; Image file.
2751 ((and (not desc) (org-export-inline-image-p
2752 link org-odt-inline-image-rules))
2753 (org-odt-link--inline-image link info))
2754 ;; Formula file.
2755 ((and (not desc) (org-export-inline-image-p
2756 link org-odt-inline-formula-rules))
2757 (org-odt-link--inline-formula link info))
2758 ;; Radio target: Transcode target's contents and use them as
2759 ;; link's description.
2760 ((string= type "radio")
2761 (let ((destination (org-export-resolve-radio-link link info)))
2762 (when destination
2763 (let ((desc (org-export-data (org-element-contents destination) info))
2764 (href (org-export-solidify-link-text path)))
2765 (format
2766 "<text:bookmark-ref text:reference-format=\"text\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2767 href desc)))))
2768 ;; Links pointing to a headline: Find destination and build
2769 ;; appropriate referencing command.
2770 ((member type '("custom-id" "fuzzy" "id"))
2771 (let* ((destination (if (string= type "fuzzy")
2772 (org-export-resolve-fuzzy-link link info)
2773 (org-export-resolve-id-link link info))))
2775 ;; Case 1: Fuzzy link points nowhere.
2776 (when (null (org-element-type destination))
2777 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2778 "Emphasis" (or desc (org-export-data
2779 (org-element-property
2780 :raw-link link) info))))
2781 ;; Case 2: Fuzzy link points to an invisible target. Strip it.
2782 (when (eq (org-element-type destination) 'keyword) "")
2783 ;; Case 3: LINK points to a headline.
2784 (when (eq (org-element-type destination) 'headline)
2785 ;; Case 3.1: LINK has a custom description that is
2786 ;; different from headline's title. Create a hyperlink.
2787 (when (and desc
2788 (let ((link-desc (org-element-contents link)))
2789 (not (string= (org-element-interpret-data link-desc)
2790 (org-element-property :raw-value
2791 destination)))))
2792 (let* ((headline-no (org-export-get-headline-number
2793 destination info))
2794 (label (format "sec-%s" (mapconcat 'number-to-string
2795 headline-no "-"))))
2796 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2797 label desc))))
2798 ;; Case 4: LINK points to an Inline image, Math formula or a Table.
2799 (let ((label-reference (ignore-errors (org-odt-format-label
2800 destination info 'reference))))
2801 (when label-reference
2802 (cond
2803 ;; Case 4.1: LINK has no description. Create a
2804 ;; cross-reference showing entity's sequence number.
2805 ((not desc) label-reference)
2806 ;; Case 4.2: LINK has description. Insert a hyperlink
2807 ;; with user-provided description.
2808 (t (let* ((caption-from (case (org-element-type destination)
2809 (link (org-export-get-parent-element
2810 destination))
2811 (t destination)))
2812 ;; Get label and caption.
2813 (label (org-element-property :name caption-from)))
2814 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2815 (org-export-solidify-link-text label) desc))))))
2816 ;; Case 5: Fuzzy link points to a TARGET.
2817 (when (eq (org-element-type destination) 'target)
2818 ;; Case 5.1: LINK has description. Create a hyperlink.
2819 (when desc
2820 (let ((label (org-element-property :value destination)))
2821 (format "<text:a xlink:type=\"simple\" xlink:href=\"#%s\">%s</text:a>"
2822 (org-export-solidify-link-text label) desc))))
2823 ;; LINK has no description. It points to either a HEADLINE, a
2824 ;; TARGET or an ELEMENT with a #+NAME: LABEL attached to it.
2825 ;; LINK to DESTINATION, but make a best effort to provide a
2826 ;; *meaningful* description.
2827 (org-odt-link--infer-description destination info))))
2828 ;; Coderef: replace link with the reference name or the
2829 ;; equivalent line number.
2830 ((string= type "coderef")
2831 (let* ((line-no (format "%d" (org-export-resolve-coderef path info)))
2832 (href (concat "coderef-" path)))
2833 (format
2834 (org-export-get-coderef-format path desc)
2835 (format
2836 "<text:bookmark-ref text:reference-format=\"number\" text:ref-name=\"OrgXref.%s\">%s</text:bookmark-ref>"
2837 href line-no))))
2838 ;; Link type is handled by a special function.
2839 ((functionp (setq protocol (nth 2 (assoc type org-link-protocols))))
2840 (funcall protocol (org-link-unescape path) desc 'odt))
2841 ;; External link with a description part.
2842 ((and path desc)
2843 (let ((link-contents (org-element-contents link)))
2844 ;; Check if description is a link to an inline image.
2845 (if (and (not (cdr link-contents))
2846 (let ((desc-element (car link-contents)))
2847 (and (eq (org-element-type desc-element) 'link)
2848 (org-export-inline-image-p
2849 desc-element org-odt-inline-image-rules))))
2850 ;; Format link as a clickable image.
2851 (format "\n<draw:a xlink:type=\"simple\" xlink:href=\"%s\">\n%s\n</draw:a>"
2852 path desc)
2853 ;; Otherwise, format it as a regular link.
2854 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2855 path desc))))
2856 ;; External link without a description part.
2857 (path
2858 (format "<text:a xlink:type=\"simple\" xlink:href=\"%s\">%s</text:a>"
2859 path path))
2860 ;; No path, only description. Try to do something useful.
2861 (t (format "<text:span text:style-name=\"%s\">%s</text:span>"
2862 "Emphasis" desc)))))
2865 ;;;; Paragraph
2867 (defun org-odt-paragraph (paragraph contents info)
2868 "Transcode a PARAGRAPH element from Org to ODT.
2869 CONTENTS is the contents of the paragraph, as a string. INFO is
2870 the plist used as a communication channel."
2871 (let* ((parent (org-export-get-parent paragraph))
2872 (parent-type (org-element-type parent))
2873 (style (case parent-type
2874 (quote-block "Quotations")
2875 (center-block "OrgCenter")
2876 (footnote-definition "Footnote")
2877 (t (or (org-element-property :style paragraph)
2878 "Text_20_body")))))
2879 ;; If this paragraph is a leading paragraph in an item and the
2880 ;; item has a checkbox, splice the checkbox and paragraph contents
2881 ;; together.
2882 (when (and (eq (org-element-type parent) 'item)
2883 (eq paragraph (car (org-element-contents parent))))
2884 (setq contents (concat (org-odt--checkbox parent) contents)))
2885 (assert style)
2886 (format "\n<text:p text:style-name=\"%s\">%s</text:p>" style contents)))
2889 ;;;; Plain List
2891 (defun org-odt-plain-list (plain-list contents info)
2892 "Transcode a PLAIN-LIST element from Org to ODT.
2893 CONTENTS is the contents of the list. INFO is a plist holding
2894 contextual information."
2895 (format "\n<text:list text:style-name=\"%s\" %s>\n%s</text:list>"
2896 ;; Choose style based on list type.
2897 (case (org-element-property :type plain-list)
2898 (ordered "OrgNumberedList")
2899 (unordered "OrgBulletedList")
2900 (descriptive-1 "OrgDescriptionList")
2901 (descriptive-2 "OrgDescriptionList"))
2902 ;; If top-level list, re-start numbering. Otherwise,
2903 ;; continue numbering.
2904 (format "text:continue-numbering=\"%s\""
2905 (let* ((parent (org-export-get-parent plain-list)))
2906 (if (and parent (eq (org-element-type parent) 'item))
2907 "true" "false")))
2908 contents))
2910 ;;;; Plain Text
2912 (defun org-odt--encode-tabs-and-spaces (line)
2913 (replace-regexp-in-string
2914 "\\([\t]\\|\\([ ]+\\)\\)"
2915 (lambda (s)
2916 (cond
2917 ((string= s "\t") "<text:tab/>")
2918 (t (let ((n (length s)))
2919 (cond
2920 ((= n 1) " ")
2921 ((> n 1) (concat " " (format "<text:s text:c=\"%d\"/>" (1- n))))
2922 (t ""))))))
2923 line))
2925 (defun org-odt--encode-plain-text (text &optional no-whitespace-filling)
2926 (mapc
2927 (lambda (pair)
2928 (setq text (replace-regexp-in-string (car pair) (cdr pair) text t t)))
2929 '(("&" . "&amp;") ("<" . "&lt;") (">" . "&gt;")))
2930 (if no-whitespace-filling text
2931 (org-odt--encode-tabs-and-spaces text)))
2933 (defun org-odt-plain-text (text info)
2934 "Transcode a TEXT string from Org to ODT.
2935 TEXT is the string to transcode. INFO is a plist holding
2936 contextual information."
2937 (let ((output text))
2938 ;; Protect &, < and >.
2939 (setq output (org-odt--encode-plain-text output t))
2940 ;; Handle smart quotes. Be sure to provide original string since
2941 ;; OUTPUT may have been modified.
2942 (setq output (org-export-activate-smart-quotes output :utf-8 info text))
2943 ;; Convert special strings.
2944 (when (plist-get info :with-special-strings)
2945 (mapc
2946 (lambda (pair)
2947 (setq output
2948 (replace-regexp-in-string (car pair) (cdr pair) output t nil)))
2949 org-odt-special-string-regexps))
2950 ;; Handle break preservation if required.
2951 (when (plist-get info :preserve-breaks)
2952 (setq output (replace-regexp-in-string
2953 "\\(\\\\\\\\\\)?[ \t]*\n" "<text:line-break/>\n" output t)))
2954 ;; Return value.
2955 output))
2958 ;;;; Planning
2960 (defun org-odt-planning (planning contents info)
2961 "Transcode a PLANNING element from Org to ODT.
2962 CONTENTS is nil. INFO is a plist used as a communication
2963 channel."
2964 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
2965 "OrgPlanning"
2966 (concat
2967 (let ((closed (org-element-property :closed planning)))
2968 (when closed
2969 (concat
2970 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2971 "OrgClosedKeyword" org-closed-string)
2972 (org-odt-timestamp closed contents info))))
2973 (let ((deadline (org-element-property :deadline planning)))
2974 (when deadline
2975 (concat
2976 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2977 "OrgDeadlineKeyword" org-deadline-string)
2978 (org-odt-timestamp deadline contents info))))
2979 (let ((scheduled (org-element-property :scheduled planning)))
2980 (when scheduled
2981 (concat
2982 (format "<text:span text:style-name=\"%s\">%s</text:span>"
2983 "OrgScheduledKeyword" org-deadline-string)
2984 (org-odt-timestamp scheduled contents info)))))))
2987 ;;;; Property Drawer
2989 (defun org-odt-property-drawer (property-drawer contents info)
2990 "Transcode a PROPERTY-DRAWER element from Org to ODT.
2991 CONTENTS is nil. INFO is a plist holding contextual
2992 information."
2993 ;; The property drawer isn't exported but we want separating blank
2994 ;; lines nonetheless.
2998 ;;;; Quote Block
3000 (defun org-odt-quote-block (quote-block contents info)
3001 "Transcode a QUOTE-BLOCK element from Org to ODT.
3002 CONTENTS holds the contents of the block. INFO is a plist
3003 holding contextual information."
3004 contents)
3007 ;;;; Quote Section
3009 (defun org-odt-quote-section (quote-section contents info)
3010 "Transcode a QUOTE-SECTION element from Org to ODT.
3011 CONTENTS is nil. INFO is a plist holding contextual information."
3012 (let ((value (org-remove-indentation
3013 (org-element-property :value quote-section))))
3014 (when value (org-odt-do-format-code value))))
3017 ;;;; Section
3019 (defun org-odt-format-section (text style &optional name)
3020 (let ((default-name (car (org-odt-add-automatic-style "Section"))))
3021 (format "\n<text:section text:style-name=\"%s\" %s>\n%s\n</text:section>"
3022 style
3023 (format "text:name=\"%s\"" (or name default-name))
3024 text)))
3027 (defun org-odt-section (section contents info) ; FIXME
3028 "Transcode a SECTION element from Org to ODT.
3029 CONTENTS holds the contents of the section. INFO is a plist
3030 holding contextual information."
3031 contents)
3033 ;;;; Radio Target
3035 (defun org-odt-radio-target (radio-target text info)
3036 "Transcode a RADIO-TARGET object from Org to ODT.
3037 TEXT is the text of the target. INFO is a plist holding
3038 contextual information."
3039 (org-odt--target
3040 text (org-export-solidify-link-text
3041 (org-element-property :value radio-target))))
3044 ;;;; Special Block
3046 (defun org-odt-special-block (special-block contents info)
3047 "Transcode a SPECIAL-BLOCK element from Org to ODT.
3048 CONTENTS holds the contents of the block. INFO is a plist
3049 holding contextual information."
3050 (let ((type (downcase (org-element-property :type special-block)))
3051 (attributes (org-export-read-attribute :attr_odt special-block)))
3052 (cond
3053 ;; Annotation.
3054 ((string= type "annotation")
3055 (let* ((author (or (plist-get attributes :author)
3056 (let ((author (plist-get info :author)))
3057 (and author (org-export-data author info)))))
3058 (date (or (plist-get attributes :date)
3059 ;; FIXME: Is `car' right thing to do below?
3060 (car (plist-get info :date)))))
3062 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3063 "Text_20_body"
3064 (format "<office:annotation>\n%s\n</office:annotation>"
3065 (concat
3066 (and author
3067 (format "<dc:creator>%s</dc:creator>" author))
3068 (and date
3069 (format "<dc:date>%s</dc:date>"
3070 (org-odt--format-timestamp date nil 'iso-date)))
3071 contents)))))
3072 ;; Textbox.
3073 ((string= type "textbox")
3074 (let ((width (plist-get attributes :width))
3075 (height (plist-get attributes :height))
3076 (style (plist-get attributes :style))
3077 (extra (plist-get attributes :extra))
3078 (anchor (plist-get attributes :anchor)))
3079 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3080 "Text_20_body" (org-odt--textbox contents width height
3081 style extra anchor))))
3082 (t contents))))
3085 ;;;; Src Block
3087 (defun org-odt-hfy-face-to-css (fn)
3088 "Create custom style for face FN.
3089 When FN is the default face, use it's foreground and background
3090 properties to create \"OrgSrcBlock\" paragraph style. Otherwise
3091 use it's color attribute to create a character style whose name
3092 is obtained from FN. Currently all attributes of FN other than
3093 color are ignored.
3095 The style name for a face FN is derived using the following
3096 operations on the face name in that order - de-dash, CamelCase
3097 and prefix with \"OrgSrc\". For example,
3098 `font-lock-function-name-face' is associated with
3099 \"OrgSrcFontLockFunctionNameFace\"."
3100 (let* ((css-list (hfy-face-to-style fn))
3101 (style-name ((lambda (fn)
3102 (concat "OrgSrc"
3103 (mapconcat
3104 'capitalize (split-string
3105 (hfy-face-or-def-to-name fn) "-")
3106 ""))) fn))
3107 (color-val (cdr (assoc "color" css-list)))
3108 (background-color-val (cdr (assoc "background" css-list)))
3109 (style (and org-odt-create-custom-styles-for-srcblocks
3110 (cond
3111 ((eq fn 'default)
3112 (format org-odt-src-block-paragraph-format
3113 background-color-val color-val))
3115 (format
3117 <style:style style:name=\"%s\" style:family=\"text\">
3118 <style:text-properties fo:color=\"%s\"/>
3119 </style:style>" style-name color-val))))))
3120 (cons style-name style)))
3122 (defun org-odt-htmlfontify-string (line)
3123 (let* ((hfy-html-quote-regex "\\([<\"&> ]\\)")
3124 (hfy-html-quote-map '(("\"" "&quot;")
3125 ("<" "&lt;")
3126 ("&" "&amp;")
3127 (">" "&gt;")
3128 (" " "<text:s/>")
3129 (" " "<text:tab/>")))
3130 (hfy-face-to-css 'org-odt-hfy-face-to-css)
3131 (hfy-optimisations-1 (copy-sequence hfy-optimisations))
3132 (hfy-optimisations (add-to-list 'hfy-optimisations-1
3133 'body-text-only))
3134 (hfy-begin-span-handler
3135 (lambda (style text-block text-id text-begins-block-p)
3136 (insert (format "<text:span text:style-name=\"%s\">" style))))
3137 (hfy-end-span-handler (lambda nil (insert "</text:span>"))))
3138 (org-no-warnings (htmlfontify-string line))))
3140 (defun org-odt-do-format-code
3141 (code &optional lang refs retain-labels num-start)
3142 (let* ((lang (or (assoc-default lang org-src-lang-modes) lang))
3143 (lang-mode (and lang (intern (format "%s-mode" lang))))
3144 (code-lines (org-split-string code "\n"))
3145 (code-length (length code-lines))
3146 (use-htmlfontify-p (and (functionp lang-mode)
3147 org-odt-fontify-srcblocks
3148 (require 'htmlfontify nil t)
3149 (fboundp 'htmlfontify-string)))
3150 (code (if (not use-htmlfontify-p) code
3151 (with-temp-buffer
3152 (insert code)
3153 (funcall lang-mode)
3154 (font-lock-fontify-buffer)
3155 (buffer-string))))
3156 (fontifier (if use-htmlfontify-p 'org-odt-htmlfontify-string
3157 'org-odt--encode-plain-text))
3158 (par-style (if use-htmlfontify-p "OrgSrcBlock"
3159 "OrgFixedWidthBlock"))
3160 (i 0))
3161 (assert (= code-length (length (org-split-string code "\n"))))
3162 (setq code
3163 (org-export-format-code
3164 code
3165 (lambda (loc line-num ref)
3166 (setq par-style
3167 (concat par-style (and (= (incf i) code-length) "LastLine")))
3169 (setq loc (concat loc (and ref retain-labels (format " (%s)" ref))))
3170 (setq loc (funcall fontifier loc))
3171 (when ref
3172 (setq loc (org-odt--target loc (concat "coderef-" ref))))
3173 (assert par-style)
3174 (setq loc (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3175 par-style loc))
3176 (if (not line-num) loc
3177 (format "\n<text:list-item>%s\n</text:list-item>" loc)))
3178 num-start refs))
3179 (cond
3180 ((not num-start) code)
3181 ((= num-start 0)
3182 (format
3183 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3184 " text:continue-numbering=\"false\"" code))
3186 (format
3187 "\n<text:list text:style-name=\"OrgSrcBlockNumberedLine\"%s>%s</text:list>"
3188 " text:continue-numbering=\"true\"" code)))))
3190 (defun org-odt-format-code (element info)
3191 (let* ((lang (org-element-property :language element))
3192 ;; Extract code and references.
3193 (code-info (org-export-unravel-code element))
3194 (code (car code-info))
3195 (refs (cdr code-info))
3196 ;; Does the src block contain labels?
3197 (retain-labels (org-element-property :retain-labels element))
3198 ;; Does it have line numbers?
3199 (num-start (case (org-element-property :number-lines element)
3200 (continued (org-export-get-loc element info))
3201 (new 0))))
3202 (org-odt-do-format-code code lang refs retain-labels num-start)))
3204 (defun org-odt-src-block (src-block contents info)
3205 "Transcode a SRC-BLOCK element from Org to ODT.
3206 CONTENTS holds the contents of the item. INFO is a plist holding
3207 contextual information."
3208 (let* ((lang (org-element-property :language src-block))
3209 (attributes (org-export-read-attribute :attr_odt src-block))
3210 (captions (org-odt-format-label src-block info 'definition))
3211 (caption (car captions)) (short-caption (cdr captions)))
3212 (concat
3213 (and caption
3214 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3215 "Listing" caption))
3216 (let ((--src-block (org-odt-format-code src-block info)))
3217 (if (not (plist-get attributes :textbox)) --src-block
3218 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3219 "Text_20_body"
3220 (org-odt--textbox --src-block nil nil nil)))))))
3223 ;;;; Statistics Cookie
3225 (defun org-odt-statistics-cookie (statistics-cookie contents info)
3226 "Transcode a STATISTICS-COOKIE object from Org to ODT.
3227 CONTENTS is nil. INFO is a plist holding contextual information."
3228 (let ((cookie-value (org-element-property :value statistics-cookie)))
3229 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3230 "OrgCode" cookie-value)))
3233 ;;;; Strike-Through
3235 (defun org-odt-strike-through (strike-through contents info)
3236 "Transcode STRIKE-THROUGH from Org to ODT.
3237 CONTENTS is the text with strike-through markup. INFO is a plist
3238 holding contextual information."
3239 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3240 "Strikethrough" contents))
3243 ;;;; Subscript
3245 (defun org-odt-subscript (subscript contents info)
3246 "Transcode a SUBSCRIPT object from Org to ODT.
3247 CONTENTS is the contents of the object. INFO is a plist holding
3248 contextual information."
3249 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3250 "OrgSubscript" contents))
3253 ;;;; Superscript
3255 (defun org-odt-superscript (superscript contents info)
3256 "Transcode a SUPERSCRIPT object from Org to ODT.
3257 CONTENTS is the contents of the object. INFO is a plist holding
3258 contextual information."
3259 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3260 "OrgSuperscript" contents))
3263 ;;;; Table Cell
3265 (defun org-odt-table-style-spec (element info)
3266 (let* ((table (org-export-get-parent-table element))
3267 (table-attributes (org-export-read-attribute :attr_odt table))
3268 (table-style (plist-get table-attributes :style)))
3269 (assoc table-style org-odt-table-styles)))
3271 (defun org-odt-get-table-cell-styles (table-cell info)
3272 "Retrieve styles applicable to a table cell.
3273 R and C are (zero-based) row and column numbers of the table
3274 cell. STYLE-SPEC is an entry in `org-odt-table-styles'
3275 applicable to the current table. It is `nil' if the table is not
3276 associated with any style attributes.
3278 Return a cons of (TABLE-CELL-STYLE-NAME . PARAGRAPH-STYLE-NAME).
3280 When STYLE-SPEC is nil, style the table cell the conventional way
3281 - choose cell borders based on row and column groupings and
3282 choose paragraph alignment based on `org-col-cookies' text
3283 property. See also
3284 `org-odt-get-paragraph-style-cookie-for-table-cell'.
3286 When STYLE-SPEC is non-nil, ignore the above cookie and return
3287 styles congruent with the ODF-1.2 specification."
3288 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3289 (r (car table-cell-address)) (c (cdr table-cell-address))
3290 (style-spec (org-odt-table-style-spec table-cell info))
3291 (table-dimensions (org-export-table-dimensions
3292 (org-export-get-parent-table table-cell)
3293 info)))
3294 (when style-spec
3295 ;; LibreOffice - particularly the Writer - honors neither table
3296 ;; templates nor custom table-cell styles. Inorder to retain
3297 ;; inter-operability with LibreOffice, only automatic styles are
3298 ;; used for styling of table-cells. The current implementation is
3299 ;; congruent with ODF-1.2 specification and hence is
3300 ;; future-compatible.
3302 ;; Additional Note: LibreOffice's AutoFormat facility for tables -
3303 ;; which recognizes as many as 16 different cell types - is much
3304 ;; richer. Unfortunately it is NOT amenable to easy configuration
3305 ;; by hand.
3306 (let* ((template-name (nth 1 style-spec))
3307 (cell-style-selectors (nth 2 style-spec))
3308 (cell-type
3309 (cond
3310 ((and (cdr (assoc 'use-first-column-styles cell-style-selectors))
3311 (= c 0)) "FirstColumn")
3312 ((and (cdr (assoc 'use-last-column-styles cell-style-selectors))
3313 (= (1+ c) (cdr table-dimensions)))
3314 "LastColumn")
3315 ((and (cdr (assoc 'use-first-row-styles cell-style-selectors))
3316 (= r 0)) "FirstRow")
3317 ((and (cdr (assoc 'use-last-row-styles cell-style-selectors))
3318 (= (1+ r) (car table-dimensions)))
3319 "LastRow")
3320 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3321 (= (% r 2) 1)) "EvenRow")
3322 ((and (cdr (assoc 'use-banding-rows-styles cell-style-selectors))
3323 (= (% r 2) 0)) "OddRow")
3324 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3325 (= (% c 2) 1)) "EvenColumn")
3326 ((and (cdr (assoc 'use-banding-columns-styles cell-style-selectors))
3327 (= (% c 2) 0)) "OddColumn")
3328 (t ""))))
3329 (concat template-name cell-type)))))
3331 (defun org-odt-table-cell (table-cell contents info)
3332 "Transcode a TABLE-CELL element from Org to ODT.
3333 CONTENTS is nil. INFO is a plist used as a communication
3334 channel."
3335 (let* ((table-cell-address (org-export-table-cell-address table-cell info))
3336 (r (car table-cell-address))
3337 (c (cdr table-cell-address))
3338 (horiz-span (or (org-export-table-cell-width table-cell info) 0))
3339 (table-row (org-export-get-parent table-cell))
3340 (custom-style-prefix (org-odt-get-table-cell-styles
3341 table-cell info))
3342 (paragraph-style
3344 (and custom-style-prefix
3345 (format "%sTableParagraph" custom-style-prefix))
3346 (concat
3347 (cond
3348 ((and (= 1 (org-export-table-row-group table-row info))
3349 (org-export-table-has-header-p
3350 (org-export-get-parent-table table-row) info))
3351 "OrgTableHeading")
3352 ((let* ((table (org-export-get-parent-table table-cell))
3353 (table-attrs (org-export-read-attribute :attr_odt table))
3354 (table-header-columns (plist-get table-attrs
3355 :header-columns)))
3356 (<= c (cond ((wholenump table-header-columns)
3357 (- table-header-columns 1))
3358 (table-header-columns 0)
3359 (t -1))))
3360 "OrgTableHeading")
3361 (t "OrgTableContents"))
3362 (capitalize (symbol-name (org-export-table-cell-alignment
3363 table-cell info))))))
3364 (cell-style-name
3366 (and custom-style-prefix (format "%sTableCell"
3367 custom-style-prefix))
3368 (concat
3369 "OrgTblCell"
3370 (when (or (org-export-table-row-starts-rowgroup-p table-row info)
3371 (zerop r)) "T")
3372 (when (org-export-table-row-ends-rowgroup-p table-row info) "B")
3373 (when (and (org-export-table-cell-starts-colgroup-p table-cell info)
3374 (not (zerop c)) ) "L"))))
3375 (cell-attributes
3376 (concat
3377 (format " table:style-name=\"%s\"" cell-style-name)
3378 (and (> horiz-span 0)
3379 (format " table:number-columns-spanned=\"%d\""
3380 (1+ horiz-span))))))
3381 (unless contents (setq contents ""))
3382 (concat
3383 (assert paragraph-style)
3384 (format "\n<table:table-cell%s>\n%s\n</table:table-cell>"
3385 cell-attributes
3386 (let ((table-cell-contents (org-element-contents table-cell)))
3387 (if (memq (org-element-type (car table-cell-contents))
3388 org-element-all-elements)
3389 contents
3390 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3391 paragraph-style contents))))
3392 (let (s)
3393 (dotimes (i horiz-span s)
3394 (setq s (concat s "\n<table:covered-table-cell/>"))))
3395 "\n")))
3398 ;;;; Table Row
3400 (defun org-odt-table-row (table-row contents info)
3401 "Transcode a TABLE-ROW element from Org to ODT.
3402 CONTENTS is the contents of the row. INFO is a plist used as a
3403 communication channel."
3404 ;; Rules are ignored since table separators are deduced from
3405 ;; borders of the current row.
3406 (when (eq (org-element-property :type table-row) 'standard)
3407 (let* ((rowgroup-tags
3408 (if (and (= 1 (org-export-table-row-group table-row info))
3409 (org-export-table-has-header-p
3410 (org-export-get-parent-table table-row) info))
3411 ;; If the row belongs to the first rowgroup and the
3412 ;; table has more than one row groups, then this row
3413 ;; belongs to the header row group.
3414 '("\n<table:table-header-rows>" . "\n</table:table-header-rows>")
3415 ;; Otherwise, it belongs to non-header row group.
3416 '("\n<table:table-rows>" . "\n</table:table-rows>"))))
3417 (concat
3418 ;; Does this row begin a rowgroup?
3419 (when (org-export-table-row-starts-rowgroup-p table-row info)
3420 (car rowgroup-tags))
3421 ;; Actual table row
3422 (format "\n<table:table-row>\n%s\n</table:table-row>" contents)
3423 ;; Does this row end a rowgroup?
3424 (when (org-export-table-row-ends-rowgroup-p table-row info)
3425 (cdr rowgroup-tags))))))
3428 ;;;; Table
3430 (defun org-odt-table-first-row-data-cells (table info)
3431 (let ((table-row
3432 (org-element-map table 'table-row
3433 (lambda (row)
3434 (unless (eq (org-element-property :type row) 'rule) row))
3435 info 'first-match))
3436 (special-column-p (org-export-table-has-special-column-p table)))
3437 (if (not special-column-p) (org-element-contents table-row)
3438 (cdr (org-element-contents table-row)))))
3440 (defun org-odt--table (table contents info)
3441 "Transcode a TABLE element from Org to ODT.
3442 CONTENTS is the contents of the table. INFO is a plist holding
3443 contextual information."
3444 (case (org-element-property :type table)
3445 ;; Case 1: table.el doesn't support export to OD format. Strip
3446 ;; such tables from export.
3447 (table.el
3448 (prog1 nil
3449 (message
3450 (concat
3451 "(ox-odt): Found table.el-type table in the source Org file."
3452 " table.el doesn't support export to ODT format."
3453 " Stripping the table from export."))))
3454 ;; Case 2: Native Org tables.
3455 (otherwise
3456 (let* ((captions (org-odt-format-label table info 'definition))
3457 (caption (car captions)) (short-caption (cdr captions))
3458 (attributes (org-export-read-attribute :attr_odt table))
3459 (custom-table-style (nth 1 (org-odt-table-style-spec table info)))
3460 (table-column-specs
3461 (function
3462 (lambda (table info)
3463 (let* ((table-style (or custom-table-style "OrgTable"))
3464 (column-style (format "%sColumn" table-style)))
3465 (mapconcat
3466 (lambda (table-cell)
3467 (let ((width (1+ (or (org-export-table-cell-width
3468 table-cell info) 0)))
3469 (s (format
3470 "\n<table:table-column table:style-name=\"%s\"/>"
3471 column-style))
3472 out)
3473 (dotimes (i width out) (setq out (concat s out)))))
3474 (org-odt-table-first-row-data-cells table info) "\n"))))))
3475 (concat
3476 ;; caption.
3477 (when caption
3478 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3479 "Table" caption))
3480 ;; begin table.
3481 (let* ((automatic-name
3482 (org-odt-add-automatic-style "Table" attributes)))
3483 (format
3484 "\n<table:table table:style-name=\"%s\"%s>"
3485 (or custom-table-style (cdr automatic-name) "OrgTable")
3486 (concat (when short-caption
3487 (format " table:name=\"%s\"" short-caption)))))
3488 ;; column specification.
3489 (funcall table-column-specs table info)
3490 ;; actual contents.
3491 "\n" contents
3492 ;; end table.
3493 "</table:table>")))))
3495 (defun org-odt-table (table contents info)
3496 "Transcode a TABLE element from Org to ODT.
3497 CONTENTS is the contents of the table. INFO is a plist holding
3498 contextual information.
3500 Use `org-odt--table' to typeset the table. Handle details
3501 pertaining to indentation here."
3502 (let* ((--element-preceded-by-table-p
3503 (function
3504 (lambda (element info)
3505 (loop for el in (org-export-get-previous-element element info t)
3506 thereis (eq (org-element-type el) 'table)))))
3507 (--walk-list-genealogy-and-collect-tags
3508 (function
3509 (lambda (table info)
3510 (let* ((genealogy (org-export-get-genealogy table))
3511 (list-genealogy
3512 (when (eq (org-element-type (car genealogy)) 'item)
3513 (loop for el in genealogy
3514 when (memq (org-element-type el)
3515 '(item plain-list))
3516 collect el)))
3517 (llh-genealogy
3518 (apply 'nconc
3519 (loop for el in genealogy
3520 when (and (eq (org-element-type el) 'headline)
3521 (org-export-low-level-p el info))
3522 collect
3523 (list el
3524 (assq 'headline
3525 (org-element-contents
3526 (org-export-get-parent el)))))))
3527 parent-list)
3528 (nconc
3529 ;; Handle list genealogy.
3530 (loop for el in list-genealogy collect
3531 (case (org-element-type el)
3532 (plain-list
3533 (setq parent-list el)
3534 (cons "</text:list>"
3535 (format "\n<text:list text:style-name=\"%s\" %s>"
3536 (case (org-element-property :type el)
3537 (ordered "OrgNumberedList")
3538 (unordered "OrgBulletedList")
3539 (descriptive-1 "OrgDescriptionList")
3540 (descriptive-2 "OrgDescriptionList"))
3541 "text:continue-numbering=\"true\"")))
3542 (item
3543 (cond
3544 ((not parent-list)
3545 (if (funcall --element-preceded-by-table-p table info)
3546 '("</text:list-header>" . "<text:list-header>")
3547 '("</text:list-item>" . "<text:list-header>")))
3548 ((funcall --element-preceded-by-table-p
3549 parent-list info)
3550 '("</text:list-header>" . "<text:list-header>"))
3551 (t '("</text:list-item>" . "<text:list-item>"))))))
3552 ;; Handle low-level headlines.
3553 (loop for el in llh-genealogy
3554 with step = 'item collect
3555 (case step
3556 (plain-list
3557 (setq step 'item) ; Flip-flop
3558 (setq parent-list el)
3559 (cons "</text:list>"
3560 (format "\n<text:list text:style-name=\"%s\" %s>"
3561 (if (org-export-numbered-headline-p
3562 el info)
3563 "OrgNumberedList"
3564 "OrgBulletedList")
3565 "text:continue-numbering=\"true\"")))
3566 (item
3567 (setq step 'plain-list) ; Flip-flop
3568 (cond
3569 ((not parent-list)
3570 (if (funcall --element-preceded-by-table-p table info)
3571 '("</text:list-header>" . "<text:list-header>")
3572 '("</text:list-item>" . "<text:list-header>")))
3573 ((let ((section? (org-export-get-previous-element
3574 parent-list info)))
3575 (and section?
3576 (eq (org-element-type section?) 'section)
3577 (assq 'table (org-element-contents section?))))
3578 '("</text:list-header>" . "<text:list-header>"))
3580 '("</text:list-item>" . "<text:list-item>")))))))))))
3581 (close-open-tags (funcall --walk-list-genealogy-and-collect-tags
3582 table info)))
3583 ;; OpenDocument schema does not permit table to occur within a
3584 ;; list item.
3586 ;; One solution - the easiest and lightweight, in terms of
3587 ;; implementation - is to put the table in an indented text box
3588 ;; and make the text box part of the list-item. Unfortunately if
3589 ;; the table is big and spans multiple pages, the text box could
3590 ;; overflow. In this case, the following attribute will come
3591 ;; handy.
3593 ;; ,---- From OpenDocument-v1.1.pdf
3594 ;; | 15.27.28 Overflow behavior
3595 ;; |
3596 ;; | For text boxes contained within text document, the
3597 ;; | style:overflow-behavior property specifies the behavior of text
3598 ;; | boxes where the containing text does not fit into the text
3599 ;; | box.
3600 ;; |
3601 ;; | If the attribute's value is clip, the text that does not fit
3602 ;; | into the text box is not displayed.
3603 ;; |
3604 ;; | If the attribute value is auto-create-new-frame, a new frame
3605 ;; | will be created on the next page, with the same position and
3606 ;; | dimensions of the original frame.
3607 ;; |
3608 ;; | If the style:overflow-behavior property's value is
3609 ;; | auto-create-new-frame and the text box has a minimum width or
3610 ;; | height specified, then the text box will grow until the page
3611 ;; | bounds are reached before a new frame is created.
3612 ;; `----
3614 ;; Unfortunately, LibreOffice-3.4.6 doesn't honor
3615 ;; auto-create-new-frame property and always resorts to clipping
3616 ;; the text box. This results in table being truncated.
3618 ;; So we solve the problem the hard (and fun) way using list
3619 ;; continuations.
3621 ;; The problem only becomes more interesting if you take in to
3622 ;; account the following facts:
3624 ;; - Description lists are simulated as plain lists.
3625 ;; - Low-level headlines can be listified.
3626 ;; - In Org-mode, a table can occur not only as a regular list
3627 ;; item, but also within description lists and low-level
3628 ;; headlines.
3630 ;; See `org-odt-translate-description-lists' and
3631 ;; `org-odt-translate-low-level-headlines' for how this is
3632 ;; tackled.
3634 (concat "\n"
3635 ;; Discontinue the list.
3636 (mapconcat 'car close-open-tags "\n")
3637 ;; Put the table in an indented section.
3638 (let* ((table (org-odt--table table contents info))
3639 (level (/ (length (mapcar 'car close-open-tags)) 2))
3640 (style (format "OrgIndentedSection-Level-%d" level)))
3641 (when table (org-odt-format-section table style)))
3642 ;; Continue the list.
3643 (mapconcat 'cdr (nreverse close-open-tags) "\n"))))
3646 ;;;; Target
3648 (defun org-odt-target (target contents info)
3649 "Transcode a TARGET object from Org to ODT.
3650 CONTENTS is nil. INFO is a plist holding contextual
3651 information."
3652 (let ((value (org-element-property :value target)))
3653 (org-odt--target "" (org-export-solidify-link-text value))))
3656 ;;;; Timestamp
3658 (defun org-odt-timestamp (timestamp contents info)
3659 "Transcode a TIMESTAMP object from Org to ODT.
3660 CONTENTS is nil. INFO is a plist used as a communication
3661 channel."
3662 (let* ((raw-value (org-element-property :raw-value timestamp))
3663 (type (org-element-property :type timestamp)))
3664 (if (not org-odt-use-date-fields)
3665 (let ((value (org-odt-plain-text
3666 (org-timestamp-translate timestamp) info)))
3667 (case (org-element-property :type timestamp)
3668 ((active active-range)
3669 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3670 "OrgActiveTimestamp" value))
3671 ((inactive inactive-range)
3672 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3673 "OrgInactiveTimestamp" value))
3674 (otherwise value)))
3675 (case type
3676 (active
3677 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3678 "OrgActiveTimestamp"
3679 (format "&lt;%s&gt;" (org-odt--format-timestamp timestamp))))
3680 (inactive
3681 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3682 "OrgInactiveTimestamp"
3683 (format "[%s]" (org-odt--format-timestamp timestamp))))
3684 (active-range
3685 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3686 "OrgActiveTimestamp"
3687 (format "&lt;%s&gt;&#x2013;&lt;%s&gt;"
3688 (org-odt--format-timestamp timestamp)
3689 (org-odt--format-timestamp timestamp 'end))))
3690 (inactive-range
3691 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3692 "OrgInactiveTimestamp"
3693 (format "[%s]&#x2013;[%s]"
3694 (org-odt--format-timestamp timestamp)
3695 (org-odt--format-timestamp timestamp 'end))))
3696 (otherwise
3697 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3698 "OrgDiaryTimestamp"
3699 (org-odt-plain-text (org-timestamp-translate timestamp)
3700 info)))))))
3703 ;;;; Underline
3705 (defun org-odt-underline (underline contents info)
3706 "Transcode UNDERLINE from Org to ODT.
3707 CONTENTS is the text with underline markup. INFO is a plist
3708 holding contextual information."
3709 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3710 "Underline" contents))
3713 ;;;; Verbatim
3715 (defun org-odt-verbatim (verbatim contents info)
3716 "Transcode a VERBATIM object from Org to ODT.
3717 CONTENTS is nil. INFO is a plist used as a communication
3718 channel."
3719 (format "<text:span text:style-name=\"%s\">%s</text:span>"
3720 "OrgCode" (org-element-property :value verbatim)))
3723 ;;;; Verse Block
3725 (defun org-odt-verse-block (verse-block contents info)
3726 "Transcode a VERSE-BLOCK element from Org to ODT.
3727 CONTENTS is verse block contents. INFO is a plist holding
3728 contextual information."
3729 ;; Add line breaks to each line of verse.
3730 (setq contents (replace-regexp-in-string
3731 "\\(<text:line-break/>\\)?[ \t]*\n"
3732 "<text:line-break/>" contents))
3733 ;; Replace tabs and spaces.
3734 (setq contents (org-odt--encode-tabs-and-spaces contents))
3735 ;; Surround it in a verse environment.
3736 (format "\n<text:p text:style-name=\"%s\">%s</text:p>"
3737 "OrgVerse" contents))
3741 ;;; Filters
3743 ;;;; LaTeX fragments
3745 (defun org-odt--translate-latex-fragments (tree backend info)
3746 (let ((processing-type (plist-get info :with-latex))
3747 (count 0))
3748 ;; Normalize processing-type to one of dvipng, mathml or verbatim.
3749 ;; If the desired converter is not available, force verbatim
3750 ;; processing.
3751 (case processing-type
3752 ((t mathml)
3753 (if (and (fboundp 'org-format-latex-mathml-available-p)
3754 (org-format-latex-mathml-available-p))
3755 (setq processing-type 'mathml)
3756 (message "LaTeX to MathML converter not available.")
3757 (setq processing-type 'verbatim)))
3758 (dvipng
3759 (unless (and (org-check-external-command "latex" "" t)
3760 (org-check-external-command "dvipng" "" t))
3761 (message "LaTeX to PNG converter not available.")
3762 (setq processing-type 'verbatim)))
3763 (otherwise
3764 (message "Unknown LaTeX option. Forcing verbatim.")
3765 (setq processing-type 'verbatim)))
3767 ;; Store normalized value for later use.
3768 (when (plist-get info :with-latex)
3769 (plist-put info :with-latex processing-type))
3770 (message "Formatting LaTeX using %s" processing-type)
3772 ;; Convert `latex-fragment's and `latex-environment's.
3773 (when (memq processing-type '(mathml dvipng))
3774 (org-element-map tree '(latex-fragment latex-environment)
3775 (lambda (latex-*)
3776 (incf count)
3777 (let* ((latex-frag (org-element-property :value latex-*))
3778 (input-file (plist-get info :input-file))
3779 (cache-dir (file-name-directory input-file))
3780 (cache-subdir (concat
3781 (case processing-type
3782 (dvipng "ltxpng/")
3783 (mathml "ltxmathml/"))
3784 (file-name-sans-extension
3785 (file-name-nondirectory input-file))))
3786 (display-msg
3787 (case processing-type
3788 (dvipng (format "Creating LaTeX Image %d..." count))
3789 (mathml (format "Creating MathML snippet %d..." count))))
3790 ;; Get an Org-style link to PNG image or the MathML
3791 ;; file.
3792 (org-link
3793 (let ((link (with-temp-buffer
3794 (insert latex-frag)
3795 (org-format-latex cache-subdir cache-dir
3796 nil display-msg
3797 nil nil processing-type)
3798 (buffer-substring-no-properties
3799 (point-min) (point-max)))))
3800 (if (not (string-match "file:\\([^]]*\\)" link))
3801 (prog1 nil (message "LaTeX Conversion failed."))
3802 link))))
3803 (when org-link
3804 ;; Conversion succeeded. Parse above Org-style link to a
3805 ;; `link' object.
3806 (let* ((link (car (org-element-map (with-temp-buffer
3807 (org-mode)
3808 (insert org-link)
3809 (org-element-parse-buffer))
3810 'link 'identity))))
3811 ;; Orphan the link.
3812 (org-element-put-property link :parent nil)
3813 (let* (
3814 (replacement
3815 (case (org-element-type latex-*)
3816 ;; Case 1: LaTeX environment.
3817 ;; Mimic a "standalone image or formula" by
3818 ;; enclosing the `link' in a `paragraph'.
3819 ;; Copy over original attributes, captions to
3820 ;; the enclosing paragraph.
3821 (latex-environment
3822 (org-element-adopt-elements
3823 (list 'paragraph
3824 (list :style "OrgFormula"
3825 :name (org-element-property :name
3826 latex-*)
3827 :caption (org-element-property :caption
3828 latex-*)))
3829 link))
3830 ;; Case 2: LaTeX fragment.
3831 ;; No special action.
3832 (latex-fragment link))))
3833 ;; Note down the object that link replaces.
3834 (org-element-put-property replacement :replaces
3835 (list (org-element-type latex-*)
3836 (list :value latex-frag)))
3837 ;; Replace now.
3838 (org-element-set-element latex-* replacement))))))
3839 info)))
3840 tree)
3843 ;;;; Description lists
3845 ;; This translator is necessary to handle indented tables in a uniform
3846 ;; manner. See comment in `org-odt--table'.
3848 (defun org-odt--translate-description-lists (tree backend info)
3849 ;; OpenDocument has no notion of a description list. So simulate it
3850 ;; using plain lists. Description lists in the exported document
3851 ;; are typeset in the same manner as they are in a typical HTML
3852 ;; document.
3854 ;; Specifically, a description list like this:
3856 ;; ,----
3857 ;; | - term-1 :: definition-1
3858 ;; | - term-2 :: definition-2
3859 ;; `----
3861 ;; gets translated in to the following form:
3863 ;; ,----
3864 ;; | - term-1
3865 ;; | - definition-1
3866 ;; | - term-2
3867 ;; | - definition-2
3868 ;; `----
3870 ;; Further effect is achieved by fixing the OD styles as below:
3872 ;; 1. Set the :type property of the simulated lists to
3873 ;; `descriptive-1' and `descriptive-2'. Map these to list-styles
3874 ;; that has *no* bullets whatsoever.
3876 ;; 2. The paragraph containing the definition term is styled to be
3877 ;; in bold.
3879 (org-element-map tree 'plain-list
3880 (lambda (el)
3881 (when (equal (org-element-property :type el) 'descriptive)
3882 (org-element-set-element
3884 (apply 'org-element-adopt-elements
3885 (list 'plain-list (list :type 'descriptive-1))
3886 (mapcar
3887 (lambda (item)
3888 (org-element-adopt-elements
3889 (list 'item (list :checkbox (org-element-property
3890 :checkbox item)))
3891 (list 'paragraph (list :style "Text_20_body_20_bold")
3892 (or (org-element-property :tag item) "(no term)"))
3893 (org-element-adopt-elements
3894 (list 'plain-list (list :type 'descriptive-2))
3895 (apply 'org-element-adopt-elements
3896 (list 'item nil)
3897 (org-element-contents item)))))
3898 (org-element-contents el)))))
3899 nil)
3900 info)
3901 tree)
3903 ;;;; List tables
3905 ;; Lists that are marked with attribute `:list-table' are called as
3906 ;; list tables. They will be rendered as a table within the exported
3907 ;; document.
3909 ;; Consider an example. The following list table
3911 ;; #+attr_odt :list-table t
3912 ;; - Row 1
3913 ;; - 1.1
3914 ;; - 1.2
3915 ;; - 1.3
3916 ;; - Row 2
3917 ;; - 2.1
3918 ;; - 2.2
3919 ;; - 2.3
3921 ;; will be exported as though it were an Org table like the one show
3922 ;; below.
3924 ;; | Row 1 | 1.1 | 1.2 | 1.3 |
3925 ;; | Row 2 | 2.1 | 2.2 | 2.3 |
3927 ;; Note that org-tables are NOT multi-line and each line is mapped to
3928 ;; a unique row in the exported document. So if an exported table
3929 ;; needs to contain a single paragraph (with copious text) it needs to
3930 ;; be typed up in a single line. Editing such long lines using the
3931 ;; table editor will be a cumbersome task. Furthermore inclusion of
3932 ;; multi-paragraph text in a table cell is well-nigh impossible.
3934 ;; A LIST-TABLE circumvents above problems.
3936 ;; Note that in the example above the list items could be paragraphs
3937 ;; themselves and the list can be arbitrarily deep.
3939 ;; Inspired by following thread:
3940 ;; https://lists.gnu.org/archive/html/emacs-orgmode/2011-03/msg01101.html
3942 ;; Translate lists to tables
3944 (defun org-odt--translate-list-tables (tree backend info)
3945 (org-element-map tree 'plain-list
3946 (lambda (l1-list)
3947 (when (org-export-read-attribute :attr_odt l1-list :list-table)
3948 ;; Replace list with table.
3949 (org-element-set-element
3950 l1-list
3951 ;; Build replacement table.
3952 (apply 'org-element-adopt-elements
3953 (list 'table '(:type org :attr_odt (":style \"GriddedTable\"")))
3954 (org-element-map l1-list 'item
3955 (lambda (l1-item)
3956 (let* ((l1-item-contents (org-element-contents l1-item))
3957 l1-item-leading-text l2-list)
3958 ;; Remove Level-2 list from the Level-item. It
3959 ;; will be subsequently attached as table-cells.
3960 (let ((cur l1-item-contents) prev)
3961 (while (and cur (not (eq (org-element-type (car cur))
3962 'plain-list)))
3963 (setq prev cur)
3964 (setq cur (cdr cur)))
3965 (when prev
3966 (setcdr prev nil)
3967 (setq l2-list (car cur)))
3968 (setq l1-item-leading-text l1-item-contents))
3969 ;; Level-1 items start a table row.
3970 (apply 'org-element-adopt-elements
3971 (list 'table-row (list :type 'standard))
3972 ;; Leading text of level-1 item define
3973 ;; the first table-cell.
3974 (apply 'org-element-adopt-elements
3975 (list 'table-cell nil)
3976 l1-item-leading-text)
3977 ;; Level-2 items define subsequent
3978 ;; table-cells of the row.
3979 (org-element-map l2-list 'item
3980 (lambda (l2-item)
3981 (apply 'org-element-adopt-elements
3982 (list 'table-cell nil)
3983 (org-element-contents l2-item)))
3984 info nil 'item))))
3985 info nil 'item))))
3986 nil)
3987 info)
3988 tree)
3991 ;;; Interactive functions
3993 (defun org-odt-create-manifest-file-entry (&rest args)
3994 (push args org-odt-manifest-file-entries))
3996 (defun org-odt-write-manifest-file ()
3997 (make-directory (concat org-odt-zip-dir "META-INF"))
3998 (let ((manifest-file (concat org-odt-zip-dir "META-INF/manifest.xml")))
3999 (with-current-buffer
4000 (let ((nxml-auto-insert-xml-declaration-flag nil))
4001 (find-file-noselect manifest-file t))
4002 (insert
4003 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
4004 <manifest:manifest xmlns:manifest=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\" manifest:version=\"1.2\">\n")
4005 (mapc
4006 (lambda (file-entry)
4007 (let* ((version (nth 2 file-entry))
4008 (extra (if (not version) ""
4009 (format " manifest:version=\"%s\"" version))))
4010 (insert
4011 (format org-odt-manifest-file-entry-tag
4012 (nth 0 file-entry) (nth 1 file-entry) extra))))
4013 org-odt-manifest-file-entries)
4014 (insert "\n</manifest:manifest>"))))
4016 (defmacro org-odt--export-wrap (out-file &rest body)
4017 `(let* ((--out-file ,out-file)
4018 (out-file-type (file-name-extension --out-file))
4019 (org-odt-xml-files '("META-INF/manifest.xml" "content.xml"
4020 "meta.xml" "styles.xml"))
4021 ;; Initialize temporary workarea. All files that end up in
4022 ;; the exported document get parked/created here.
4023 (org-odt-zip-dir (file-name-as-directory
4024 (make-temp-file (format "%s-" out-file-type) t)))
4025 (org-odt-manifest-file-entries nil)
4026 (--cleanup-xml-buffers
4027 (function
4028 (lambda nil
4029 ;; Kill all XML buffers.
4030 (mapc (lambda (file)
4031 (let ((buf (find-buffer-visiting
4032 (concat org-odt-zip-dir file))))
4033 (when buf
4034 (with-current-buffer buf
4035 (set-buffer-modified-p nil)
4036 (kill-buffer buf)))))
4037 org-odt-xml-files)
4038 ;; Delete temporary directory and also other embedded
4039 ;; files that get copied there.
4040 (delete-directory org-odt-zip-dir t)))))
4041 (condition-case err
4042 (progn
4043 (unless (executable-find "zip")
4044 ;; Not at all OSes ship with zip by default
4045 (error "Executable \"zip\" needed for creating OpenDocument files"))
4046 ;; Do export. This creates a bunch of xml files ready to be
4047 ;; saved and zipped.
4048 (progn ,@body)
4049 ;; Create a manifest entry for content.xml.
4050 (org-odt-create-manifest-file-entry "text/xml" "content.xml")
4051 ;; Write mimetype file
4052 (let* ((mimetypes
4053 '(("odt" . "application/vnd.oasis.opendocument.text")
4054 ("odf" . "application/vnd.oasis.opendocument.formula")))
4055 (mimetype (cdr (assoc-string out-file-type mimetypes t))))
4056 (unless mimetype
4057 (error "Unknown OpenDocument backend %S" out-file-type))
4058 (write-region mimetype nil (concat org-odt-zip-dir "mimetype"))
4059 (org-odt-create-manifest-file-entry mimetype "/" "1.2"))
4060 ;; Write out the manifest entries before zipping
4061 (org-odt-write-manifest-file)
4062 ;; Save all XML files.
4063 (mapc (lambda (file)
4064 (let ((buf (find-buffer-visiting
4065 (concat org-odt-zip-dir file))))
4066 (when buf
4067 (with-current-buffer buf
4068 ;; Prettify output if needed.
4069 (when org-odt-prettify-xml
4070 (indent-region (point-min) (point-max)))
4071 (save-buffer 0)))))
4072 org-odt-xml-files)
4073 ;; Run zip.
4074 (let* ((target --out-file)
4075 (target-name (file-name-nondirectory target))
4076 (cmds `(("zip" "-mX0" ,target-name "mimetype")
4077 ("zip" "-rmTq" ,target-name "."))))
4078 ;; If a file with same name as the desired output file
4079 ;; exists, remove it.
4080 (when (file-exists-p target)
4081 (delete-file target))
4082 ;; Zip up the xml files.
4083 (let ((coding-system-for-write 'no-conversion) exitcode err-string)
4084 (message "Creating ODT file...")
4085 ;; Switch temporarily to content.xml. This way Zip
4086 ;; process will inherit `org-odt-zip-dir' as the current
4087 ;; directory.
4088 (with-current-buffer
4089 (find-file-noselect (concat org-odt-zip-dir "content.xml") t)
4090 (mapc
4091 (lambda (cmd)
4092 (message "Running %s" (mapconcat 'identity cmd " "))
4093 (setq err-string
4094 (with-output-to-string
4095 (setq exitcode
4096 (apply 'call-process (car cmd)
4097 nil standard-output nil (cdr cmd)))))
4098 (or (zerop exitcode)
4099 (error (concat "Unable to create OpenDocument file."
4100 (format " Zip failed with error (%s)"
4101 err-string)))))
4102 cmds)))
4103 ;; Move the zip file from temporary work directory to
4104 ;; user-mandated location.
4105 (rename-file (concat org-odt-zip-dir target-name) target)
4106 (message "Created %s" (expand-file-name target))
4107 ;; Cleanup work directory and work files.
4108 (funcall --cleanup-xml-buffers)
4109 ;; Open the OpenDocument file in archive-mode for
4110 ;; examination.
4111 (find-file-noselect target t)
4112 ;; Return exported file.
4113 (cond
4114 ;; Case 1: Conversion desired on exported file. Run the
4115 ;; converter on the OpenDocument file. Return the
4116 ;; converted file.
4117 (org-odt-preferred-output-format
4118 (or (org-odt-convert target org-odt-preferred-output-format)
4119 target))
4120 ;; Case 2: No further conversion. Return exported
4121 ;; OpenDocument file.
4122 (t target))))
4123 (error
4124 ;; Cleanup work directory and work files.
4125 (funcall --cleanup-xml-buffers)
4126 (message "OpenDocument export failed: %s"
4127 (error-message-string err))))))
4130 ;;;; Export to OpenDocument formula
4132 ;;;###autoload
4133 (defun org-odt-export-as-odf (latex-frag &optional odf-file)
4134 "Export LATEX-FRAG as OpenDocument formula file ODF-FILE.
4135 Use `org-create-math-formula' to convert LATEX-FRAG first to
4136 MathML. When invoked as an interactive command, use
4137 `org-latex-regexps' to infer LATEX-FRAG from currently active
4138 region. If no LaTeX fragments are found, prompt for it. Push
4139 MathML source to kill ring, if `org-export-copy-to-kill-ring' is
4140 non-nil."
4141 (interactive
4142 `(,(let (frag)
4143 (setq frag (and (setq frag (and (region-active-p)
4144 (buffer-substring (region-beginning)
4145 (region-end))))
4146 (loop for e in org-latex-regexps
4147 thereis (when (string-match (nth 1 e) frag)
4148 (match-string (nth 2 e) frag)))))
4149 (read-string "LaTeX Fragment: " frag nil frag))
4150 ,(let ((odf-filename (expand-file-name
4151 (concat
4152 (file-name-sans-extension
4153 (or (file-name-nondirectory buffer-file-name)))
4154 "." "odf")
4155 (file-name-directory buffer-file-name))))
4156 (read-file-name "ODF filename: " nil odf-filename nil
4157 (file-name-nondirectory odf-filename)))))
4158 (let ((filename (or odf-file
4159 (expand-file-name
4160 (concat
4161 (file-name-sans-extension
4162 (or (file-name-nondirectory buffer-file-name)))
4163 "." "odf")
4164 (file-name-directory buffer-file-name)))))
4165 (org-odt--export-wrap
4166 filename
4167 (let* ((buffer (progn
4168 (require 'nxml-mode)
4169 (let ((nxml-auto-insert-xml-declaration-flag nil))
4170 (find-file-noselect (concat org-odt-zip-dir
4171 "content.xml") t))))
4172 (coding-system-for-write 'utf-8)
4173 (save-buffer-coding-system 'utf-8))
4174 (set-buffer buffer)
4175 (set-buffer-file-coding-system coding-system-for-write)
4176 (let ((mathml (org-create-math-formula latex-frag)))
4177 (unless mathml (error "No Math formula created"))
4178 (insert mathml)
4179 ;; Add MathML to kill ring, if needed.
4180 (when org-export-copy-to-kill-ring
4181 (org-kill-new (buffer-string))))))))
4183 ;;;###autoload
4184 (defun org-odt-export-as-odf-and-open ()
4185 "Export LaTeX fragment as OpenDocument formula and immediately open it.
4186 Use `org-odt-export-as-odf' to read LaTeX fragment and OpenDocument
4187 formula file."
4188 (interactive)
4189 (org-open-file (call-interactively 'org-odt-export-as-odf) 'system))
4192 ;;;; Export to OpenDocument Text
4194 ;;;###autoload
4195 (defun org-odt-export-to-odt (&optional async subtreep visible-only ext-plist)
4196 "Export current buffer to a ODT file.
4198 If narrowing is active in the current buffer, only export its
4199 narrowed part.
4201 If a region is active, export that region.
4203 A non-nil optional argument ASYNC means the process should happen
4204 asynchronously. The resulting file should be accessible through
4205 the `org-export-stack' interface.
4207 When optional argument SUBTREEP is non-nil, export the sub-tree
4208 at point, extracting information from the headline properties
4209 first.
4211 When optional argument VISIBLE-ONLY is non-nil, don't export
4212 contents of hidden elements.
4214 EXT-PLIST, when provided, is a property list with external
4215 parameters overriding Org default settings, but still inferior to
4216 file-local settings.
4218 Return output file's name."
4219 (interactive)
4220 (let ((outfile (org-export-output-file-name ".odt" subtreep)))
4221 (if async
4222 (org-export-async-start (lambda (f) (org-export-add-to-stack f 'odt))
4223 `(expand-file-name
4224 (org-odt--export-wrap
4225 ,outfile
4226 (let* ((org-odt-embedded-images-count 0)
4227 (org-odt-embedded-formulas-count 0)
4228 (org-odt-automatic-styles nil)
4229 (org-odt-object-counters nil)
4230 ;; Let `htmlfontify' know that we are interested in
4231 ;; collecting styles.
4232 (hfy-user-sheet-assoc nil))
4233 ;; Initialize content.xml and kick-off the export
4234 ;; process.
4235 (let ((out-buf
4236 (progn
4237 (require 'nxml-mode)
4238 (let ((nxml-auto-insert-xml-declaration-flag nil))
4239 (find-file-noselect
4240 (concat org-odt-zip-dir "content.xml") t)))))
4241 (org-export-to-buffer
4242 'odt out-buf ,subtreep ,visible-only nil ',ext-plist))))))
4243 (org-odt--export-wrap
4244 outfile
4245 (let* ((org-odt-embedded-images-count 0)
4246 (org-odt-embedded-formulas-count 0)
4247 (org-odt-automatic-styles nil)
4248 (org-odt-object-counters nil)
4249 ;; Let `htmlfontify' know that we are interested in collecting
4250 ;; styles.
4251 (hfy-user-sheet-assoc nil))
4252 ;; Initialize content.xml and kick-off the export process.
4253 (let ((out-buf (progn
4254 (require 'nxml-mode)
4255 (let ((nxml-auto-insert-xml-declaration-flag nil))
4256 (find-file-noselect
4257 (concat org-odt-zip-dir "content.xml") t)))))
4258 (org-export-to-buffer
4259 'odt out-buf subtreep visible-only nil ext-plist)))))))
4262 ;;;; Convert between OpenDocument and other formats
4264 (defun org-odt-reachable-p (in-fmt out-fmt)
4265 "Return non-nil if IN-FMT can be converted to OUT-FMT."
4266 (catch 'done
4267 (let ((reachable-formats (org-odt-do-reachable-formats in-fmt)))
4268 (dolist (e reachable-formats)
4269 (let ((out-fmt-spec (assoc out-fmt (cdr e))))
4270 (when out-fmt-spec
4271 (throw 'done (cons (car e) out-fmt-spec))))))))
4273 (defun org-odt-do-convert (in-file out-fmt &optional prefix-arg)
4274 "Workhorse routine for `org-odt-convert'."
4275 (require 'browse-url)
4276 (let* ((in-file (expand-file-name (or in-file buffer-file-name)))
4277 (dummy (or (file-readable-p in-file)
4278 (error "Cannot read %s" in-file)))
4279 (in-fmt (file-name-extension in-file))
4280 (out-fmt (or out-fmt (error "Output format unspecified")))
4281 (how (or (org-odt-reachable-p in-fmt out-fmt)
4282 (error "Cannot convert from %s format to %s format?"
4283 in-fmt out-fmt)))
4284 (convert-process (car how))
4285 (out-file (concat (file-name-sans-extension in-file) "."
4286 (nth 1 (or (cdr how) out-fmt))))
4287 (extra-options (or (nth 2 (cdr how)) ""))
4288 (out-dir (file-name-directory in-file))
4289 (cmd (format-spec convert-process
4290 `((?i . ,(shell-quote-argument in-file))
4291 (?I . ,(browse-url-file-url in-file))
4292 (?f . ,out-fmt)
4293 (?o . ,out-file)
4294 (?O . ,(browse-url-file-url out-file))
4295 (?d . , (shell-quote-argument out-dir))
4296 (?D . ,(browse-url-file-url out-dir))
4297 (?x . ,extra-options)))))
4298 (when (file-exists-p out-file)
4299 (delete-file out-file))
4301 (message "Executing %s" cmd)
4302 (let ((cmd-output (shell-command-to-string cmd)))
4303 (message "%s" cmd-output))
4305 (cond
4306 ((file-exists-p out-file)
4307 (message "Exported to %s" out-file)
4308 (when prefix-arg
4309 (message "Opening %s..." out-file)
4310 (org-open-file out-file 'system))
4311 out-file)
4313 (message "Export to %s failed" out-file)
4314 nil))))
4316 (defun org-odt-do-reachable-formats (in-fmt)
4317 "Return verbose info about formats to which IN-FMT can be converted.
4318 Return a list where each element is of the
4319 form (CONVERTER-PROCESS . OUTPUT-FMT-ALIST). See
4320 `org-odt-convert-processes' for CONVERTER-PROCESS and see
4321 `org-odt-convert-capabilities' for OUTPUT-FMT-ALIST."
4322 (let* ((converter
4323 (and org-odt-convert-process
4324 (cadr (assoc-string org-odt-convert-process
4325 org-odt-convert-processes t))))
4326 (capabilities
4327 (and org-odt-convert-process
4328 (cadr (assoc-string org-odt-convert-process
4329 org-odt-convert-processes t))
4330 org-odt-convert-capabilities))
4331 reachable-formats)
4332 (when converter
4333 (dolist (c capabilities)
4334 (when (member in-fmt (nth 1 c))
4335 (push (cons converter (nth 2 c)) reachable-formats))))
4336 reachable-formats))
4338 (defun org-odt-reachable-formats (in-fmt)
4339 "Return list of formats to which IN-FMT can be converted.
4340 The list of the form (OUTPUT-FMT-1 OUTPUT-FMT-2 ...)."
4341 (let (l)
4342 (mapc (lambda (e) (add-to-list 'l e))
4343 (apply 'append (mapcar
4344 (lambda (e) (mapcar 'car (cdr e)))
4345 (org-odt-do-reachable-formats in-fmt))))
4348 (defun org-odt-convert-read-params ()
4349 "Return IN-FILE and OUT-FMT params for `org-odt-do-convert'.
4350 This is a helper routine for interactive use."
4351 (let* ((input (if (featurep 'ido) 'ido-completing-read 'completing-read))
4352 (in-file (read-file-name "File to be converted: "
4353 nil buffer-file-name t))
4354 (in-fmt (file-name-extension in-file))
4355 (out-fmt-choices (org-odt-reachable-formats in-fmt))
4356 (out-fmt
4357 (or (and out-fmt-choices
4358 (funcall input "Output format: "
4359 out-fmt-choices nil nil nil))
4360 (error
4361 "No known converter or no known output formats for %s files"
4362 in-fmt))))
4363 (list in-file out-fmt)))
4365 ;;;###autoload
4366 (defun org-odt-convert (&optional in-file out-fmt prefix-arg)
4367 "Convert IN-FILE to format OUT-FMT using a command line converter.
4368 IN-FILE is the file to be converted. If unspecified, it defaults
4369 to variable `buffer-file-name'. OUT-FMT is the desired output
4370 format. Use `org-odt-convert-process' as the converter.
4371 If PREFIX-ARG is non-nil then the newly converted file is opened
4372 using `org-open-file'."
4373 (interactive
4374 (append (org-odt-convert-read-params) current-prefix-arg))
4375 (org-odt-do-convert in-file out-fmt prefix-arg))
4377 ;;; Library Initializations
4379 (mapc
4380 (lambda (desc)
4381 ;; Let Emacs open all OpenDocument files in archive mode
4382 (add-to-list 'auto-mode-alist
4383 (cons (concat "\\." (car desc) "\\'") 'archive-mode)))
4384 org-odt-file-extensions)
4386 (provide 'ox-odt)
4388 ;; Local variables:
4389 ;; generated-autoload-file: "org-loaddefs.el"
4390 ;; End:
4392 ;;; ox-odt.el ends here