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