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