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