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