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