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