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