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