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