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