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