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