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