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