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